如果我有一个带有模板方法的模板基类:
template <typename T>
class S
{
public:
template <typename U>
void f(U p, typename enable_if<is_same<T, U> >::type*dummy = 0)
{
std::cout << p << std::endl;
}
};
对于这个例子,我简化了该方法:仅当 T == U 时它才必须“存在”
如果A是这个类:
class A : public S<int> {};
然后我就有了我想要的:
int i = 1;
A a;
a.f(i);
编译,但是
double d = 2.0;
a.f(d);
无法编译:错误:没有调用“A::f(double&)”的匹配函数 这是预期的行为。
现在让 A 继承 S<double>
还有:
class A : public S<int>, public S<double> {};
那么以下代码无法编译:
int i = 1;
A a;
a.f(i);
error: request for member ‘f’ is ambiguous error: candidates are: template<class U> void S::f(U, typename boost::enable_if<boost::is_same<T, U>, void>::type*) [with U = U, T = double] error: template<class U> void S::f(U, typename boost::enable_if<boost::is_same<T, U>, void>::type*) [with U = U, T = int]
我预计没有任何歧义:f<int>
仅存在于S<int>
在编译错误中,我们可以注意到这段代码编译时知道了 T,但不知道 U (U = U)。
有什么解释或“解决方法”吗?
最佳答案
试试这个:
a.S<int>::f(i);
...或者将函数注入(inject)到 A
中,例如
class A : public S<int>, public S<double>
{
public:
using S<int>::f;
using S<double>::f;
};
关于c++ - 启用_if : case of templated method of a template base inherited several times,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7837618/