【发布时间】:2018-05-23 22:42:10
【问题描述】:
我有一个小程序如下:
#include <iostream>
template <typename T>
class X{
public:
bool something(){
return true;
}
};
class A: public X<A>{
};
class B: public A, public X<B>{
};
template <typename T>
bool use(T &t)
{
return t.something();
}
int main()
{
B b;
std::cout << "use returned: " << use(b);
}
这不会编译,因为对于应该选择something() 的两个可能版本中的哪一个存在歧义:
In instantiation of 'bool use(T&) [with T = B]': 30:43: required from here 22:20: error: request for member 'something' is ambiguous 6:14: note: candidates are: bool X<T>::something() [with T = B] 6:14: note: bool X<T>::something() [with T = A] In function 'bool use(T&) [with T = B]': 23:1: warning: control reaches end of non-void function [-Wreturn-type]
我的问题是,如果我唯一可以编辑的地方是 use() 的正文,我该如何解决这种歧义?
【问题讨论】:
-
您可以将其转换为 X
或 A 对象。例如 ((A)t).something() -
我有点不确定演员阵容会是什么样子。只是好老(mytype)?
-
是的
((sometype)t).something()确保您拥有正确的()操作员顺序。 -
如果这不起作用,请告诉我(我测试过它确实有效)我还有其他一些建议您可以尝试。
-
你想调用哪个版本的东西?
标签: c++ templates inheritance methods ambiguous