SFINAE用于类成员函数(一个不编译另一个) [英] SFINAE for class member function (one compiles the other not)
问题描述
为什么类A
编译而类B
没有编译,编译器抱怨有两个声明,都不都是依靠SFINAE吗?
在使用 foo
时,两者实际上都应该使用模板类型推导?
Why is class A
compiling and class B
not compiling, where the compiler complains about having two declarations, are not both relying on SFINAE?
Both should actually use template type deduction when using foo
?
所以问题是,这两个版本
的细微差别以及为什么 A类
成功使用sfinae ...?
So the question really is, whats the subtle different in these two version
and why is class A
successfully using sfinae...?
- A类使用默认值(零)匿名(不必要)非类型
模板参数 - B类使用默认类型(带有enable_if)匿名 类型模板参数
- Class A uses a value-defaulted (zero) annonymous (not necessary) non-type template parameter
- Class B uses a type-defaulted (with enable_if) annonymous type template parameter
代码:
template<typename T>
struct A
{
template<typename U,
typename std::enable_if<!std::is_floating_point<U>::value>::type * = nullptr
>
void foo() {}
template<typename U,
typename std::enable_if<std::is_floating_point<U>::value>::type * = nullptr
>
void foo() {}
};
template<typename T>
struct B
{
template<typename U,
typename = typename std::enable_if<!std::is_floating_point<U>::value>::type
>
void foo() {}
template<typename U,
typename = typename std::enable_if<std::is_floating_point<U>::value>::type
>
void foo() {}
};
实时代码位于: http://coliru.stacked-crooked.com/a/40ec5efc7ba2a47c
推荐答案
§1.3.22定义功能模板的签名:
§1.3.22 defines the signature of a function template:
签名
<
类成员函数模板>
名称,参数类型列表(8.3.5),该函数所属的类成员,
cv限定词(如果有),ref限定词(如果有),返回类型和
模板参数列表
signature
<
class member function template>
name, parameter type list (8.3.5), class of which the function is a member, cv-qualifiers (if any), ref-qualifier (if any), return type, and template parameter list
模板参数列表不包括给定的默认参数。对于 A :: foo
,模板参数不等效(在14.5.6.1节中精确定义的术语)。在 B :: foo
中。您只是用不同的默认参数声明了相同的函数模板-从而违反了§9.2/ 1和§14.1/ 12。
The template parameter list does not include the default arguments given. For A::foo
, the template parameters are not equivalent (a term precisely defined in §14.5.6.1). In B::foo
, they are. You're simply declaring the same function template with different default arguments - and thereby violate both §9.2/1 and §14.1/12.
仅通过 enable_if
的条件重载函数模板时,这是一个常见问题。特别是对于构造函数,您不能将 enable_if
部分放在返回值中。
This is a common problem when overloading function templates solely by a condition for enable_if
. In particular for constructors, where you can't place the enable_if
part in the return value.
这篇关于SFINAE用于类成员函数(一个不编译另一个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!