在函数重载中使用标签
为什么 X 中的方法测试不明确,如何解决这个问题?
struct A{};
struct B{};
template<typename T>
struct I { void test(T){} };
struct X : public I<A>, I<B> {};
int main(int argc, const char *argv[])
{
X x;
x.test(A());
return 0;
}
编译错误:
In function ‘int main(int, const char**)’:
error: request for member ‘test’ is ambiguous
error: candidates are: void I<T>::test(T) [with T = B]
error: void I<T>::test(T) [with T = A]
Why is method test in X ambiguous, and how can this be fixed?
struct A{};
struct B{};
template<typename T>
struct I { void test(T){} };
struct X : public I<A>, I<B> {};
int main(int argc, const char *argv[])
{
X x;
x.test(A());
return 0;
}
Compile error:
In function ‘int main(int, const char**)’:
error: request for member ‘test’ is ambiguous
error: candidates are: void I<T>::test(T) [with T = B]
error: void I<T>::test(T) [with T = A]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
test
是不明确的,因为它是X
的两个基类的成员。虽然两个函数并不匹配,但名称匹配。使用显式转发修复:
test
is ambiguous because it is a member of two base classes ofX
. While not both functions match, the name matches.Fix with an explicit forward:
使用 using:
gcc 错误
request for member 'test' is ambigacy
在这里并不是最好的,我们可以更好地看到 clang:member 'test' found in 错误的含义不同类型的多个基类
Use using:
The gcc error
request for member 'test' is ambiguous
is not really the best here, we can see better what is meant with the error of clang:member 'test' found in multiple base classes of different types
由于
X
乘法继承自I
和I
,因此对test()
的调用为模糊的。您可以这样做来显式声明您所指的是哪个父级:Because
X
multiply inherits fromI<A>
andI<B>
, the call totest()
is ambiguous. You can do this to explicitly declare which parent you are referring to: