【发布时间】:2016-08-12 08:46:08
【问题描述】:
考虑到一个 C++ 模板 mixin 结构,我如何编写一个函数来接受一个带有特定组件的 mixin?在这个例子中,如何将withAandB 给worksWithA()?
struct Base {};
template <class T>
struct HasA : T
{
int A;
};
template <class T>
struct HasB : T
{
int B;
};
void WorksWithA(HasA<Base> &p)
{
p.A++;
}
void WorksWithAandB(HasA<HasB<Base> > &p)
{
p.A++;
p.B++;
}
int _tmain(int argc, _TCHAR *argv[])
{
HasA<Base> withA;
HasA<HasB<Base> > withAandB;
WorksWithA(withA); // OK
WorksWithAandB(withAandB); // OK
WorksWithA(withAandB); // KO, no conversion available
return 0;
}
即使抛开构造问题或 mixin 排序问题(HasA<HasB<Base>> 与 HasB<HasA<Base>>),除了将其设为模板之外,我看不到编写此函数的好方法。
我目前处于没有 C++11 的环境中,但如果现代 C++ 提供解决方案,我会很感兴趣。
非常感谢!
【问题讨论】: