所以基本上我想定义一个从任意数量的类继承的类,并在其中有一个方法来调用所有基类的重载方法。
我试着写这个,但它不会编译:
class Foo
{
public:
void method()
{
std::cout << "Foo::method()\n";
}
};
class Bar
{
public:
void method()
{
std::cout << "Bar::method()\n";
}
};
template <typename... Ts>
class Combined: public Ts...
{
public:
Combined(const Ts&... ts): Ts(ts)... {}
Combined(Ts&&... ts): Ts(std::move(ts))... {}
template <typename U>
void call_methods()
{
U::method();
}
template <typename U, typename... Us>
void call_methods()
{
U::method();
call_methods<Us...>();
}
void method()
{
call_methods<Ts...>();
}
};
int main(int argc, char *argv[])
{
Combined<Foo, Bar> obj({}, {});
obj.method();
return 0;
}
编译器说如下:
test.cpp:42:9: error: call to member function 'call_methods' is ambiguous
call_methods<Us...>();
^~~~~~~~~~~~~~~~~~~
test.cpp:47:9: note: in instantiation of function template specialization
'Combined<Foo, Bar>::call_methods<Foo, Bar>' requested here
call_methods<Ts...>();
^
test.cpp:57:9: note: in instantiation of member function
'Combined<Foo, Bar>::method' requested here
obj.method();
^
test.cpp:33:10: note: candidate function [with U = Bar]
void call_methods()
^
test.cpp:39:10: note: candidate function [with U = Bar, Us = <>]
void call_methods()
^
call_methods<U = Bar>
和之间基本上存在歧义call_methods<U = Bar, Us = <>>
。但是如果我声明 a void call_methods() {}
,它会call_methods<Us...>();
由于某种原因与 the 不匹配。
如果还不清楚,我想Combined<Foo, Bar>::method()
打电话给Foo::method()
和Bar::method()
。
我知道我可以通过将tuple
相应类型的对象作为成员并对其进行迭代来实现这一点,但我真的很想找到一个更接近我所写的解决方案。
要修复您的解决方案,请在参数包为空时禁用第二个重载:
template <typename U, typename... Us>
typename std::enable_if< (sizeof...(Us) > 0) >::type
call_methods()
{
U::method();
call_methods<Us...>();
}
摆脱歧义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句