c++ - SFINAE:当成员函数不是模板时,没有名为 ‘type’ 的类型

标签 c++ sfinae

考虑以下示例:

template <typename T>
struct Boo {

    template <typename K = T>
    static typename enable_if<is_same<K, X1>::value, void>::type foo (int, int) {}

    template <typename K = T>
    static typename enable_if<is_same<K, X2>::value, void>::type foo (int) {}
};

template <typename T>
struct Goo {
    static typename enable_if<is_same<T, X1>::value, void>::type foo (int, int) {}

    static typename enable_if<is_same<T, X2>::value, void>::type foo (int) {}
};

及用法:

Boo<X1>::foo (1, 1);
Boo<X1>::foo (1);       // (1)
Boo<X2>::foo (5);
Boo<X2>::foo (5, 5);    // (2)

Goo<X1>::foo (1, 2);    // (3)
Goo<X2>::foo (2);       // (4)

(1) 和 (2) 无法编译,这就是我想要的,但是有人可以解释一下为什么 (3) 和 (4) 无法编译吗?那么,为什么 Goo::foo (int, int)Goo::foo (int) 如果它们不是模板,就不能像 一样使用>Boo::foo (int, int), Boo::foo (int)

最佳答案

答案非常简单 - SFINAE 致力于函数本身。它对它们的收容等级不起作用。由于在第二种情况下,函数本身不是模板,因此它们的实例是在实例化类时创建的 - 并且所有类型都必须正确。只有模板函数可以从重载决策中简单地丢弃。

小插图。即使这段代码也无法编译:

Goo<X1> a;

这里根本没有调用任何函数,但是代码将无法编译 - 因为编译器将无法创建类实例所需的函数。

关于c++ - SFINAE:当成员函数不是模板时,没有名为 ‘type’ 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33424646/

相关文章:

用于元编程的 C++ STL 函数等价物

c++ - SFINAE 检查继承的成员函数

C++ 如何通过可选的 typedef、使用 SFINAE 或其他方式选择类

c++ - 为什么这种替代失败发生在基于 SFINAE 的反射中?

c++ - ShowWindow 无效的窗口句柄

c++ - 如何区分 llvm IR 代码中的堆栈/堆地址?

c++ - _beginthread 在父构造函数中

c++ - 设计内存覆盖检测工具

c++ - 模板成员函数上的外线 sfinae 是否可能?

c++ - 如何为 QWebEngineView 设置 OffTheRecord 配置文件?