[英]SFINAE: no type named ‘type’ when member function is not a template
Consider following example: 考虑以下示例:
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) {}
};
And usage: 用法:
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) and (2) don't compile and this is what I wanted, but could someone explain me why (3) and (4) can not be compiled? (1)和(2)不编译,这是我想要的,但有人可以解释为什么(3)和(4)不能编译? So, why
Goo::foo (int, int)
and Goo::foo (int)
if they are not templates, can not be used the same way as Boo::foo (int, int)
, Boo::foo (int)
. 那么,为什么
Goo::foo (int, int)
和Goo::foo (int)
如果不是模板,就不能像Boo::foo (int, int)
, Boo::foo (int)
。
The answer is very simple - SFINAE works on functions themsleves. 答案非常简单 - SFINAE在函数上运行。 It does not work on their containment classes.
它不适用于他们的收容类。 Since in the second case the functions themselves are not templates, their instances are created when the class is instantiated - and all the types must be correct.
由于在第二种情况下,函数本身不是模板,因此在实例化类时会创建它们的实例 - 并且所有类型都必须正确。 Only template functions can be simply discarded from overload resolution.
只能从重载决策中丢弃模板函数。
Small illustration. 小插图。 Even this code will fail to compile:
即使这段代码也无法编译:
Goo<X1> a;
There is no function called here at all, yet the code will fail to compile - because compiler will not be able to create the functions required for the class instance. 这里没有调用任何函数,但代码将无法编译 - 因为编译器将无法创建类实例所需的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.