我有一个小程序如下:
#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()
的身体,我怎么能解决这种歧义?
是。例如,您可以将调用限定为something
(godbolt):
template <typename T>
bool use(T &t)
{
return t.A::something();
}
您可以为T派生自X然后转换为X内部的情况添加模板“use”的特化。
template <typename T>
class X{
public:
bool something(){
return true;
}
};
class A: public X<A>{
};
class B: public A, public X<B>{
};
#
# If class derives from X<T> make sure to cast to X<T> before calling something
#
template<typename T>
typename std::enable_if<std::is_base_of<X<T>, T>::value, bool>::type use(T &t)
{
return static_cast<X<T>&>(t).something();
}
#
# This gets run for everything that doesn't derive from X<T>
#
template<typename T>
typename std::enable_if<!std::is_base_of<X<T>, T>::value, bool>::type use(T &t)
{
return t.something();
}
但是必须检查语法,但是这应该确保你在特殊情况下得到它,同时只允许一个“某事”调用。