c++ - 启用_if : case of templated method of a template base inherited several times

标签 c++ templates boost enable-if

如果我有一个带有模板方法的模板基类:

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/

相关文章:

c++ - 覆盖虚函数时的异常规范?

C++:处理许多配置变量的设计建议

templates - MediaWiki以及如何通过模板获取页面列表

c++ - Boost mutex 在等待线程关闭时抛出错误

c++ - boost::asio 内部线程

multithreading - 在多线程世界中使用带有shared_ptr向量的std::sort的危险

c++ - 为 Intellisense/对象浏览器等记录 COM 对象

c++ - 为什么我不能在 struct 中初始化 char 数组

c++ - 遍历通用 STL 容器以检查是否存在

c++ - MFC 错误如 A reference that is not to 'const' cannot be bound to a non-lvalue