使用 enable_if 选择类构造函数
考虑以下代码:
#include <iostream>
#include <type_traits>
template <typename T>
struct A {
int val = 0;
template <class = typename std::enable_if<T::value>::type>
A(int n) : val(n) {};
A(...) { }
/* ... */
};
struct YES { constexpr static bool value = true; };
struct NO { constexpr static bool value = false; };
int main() {
A<YES> y(10);
A<NO> n;
std::cout << "YES: " << y.val << std::endl
<< "NO: " << n.val << std::endl;
}
我想有选择地定义构造函数 A::A(int) 仅用于使用 enable_if 的某些类型.对于所有其他类型,默认构造函数 A::A(...) 应该是替换失败时编译器的默认情况.然而,这对我来说很有意义,编译器(gcc 版本 4.9.0 20130714)仍在抱怨
I want to selectively define constructor A::A(int) only for some types using enable_if. For all other types there is default constructor A::A(...) which should be the default case for compiler when substitution fails. However this makes sense for me compiler (gcc version 4.9.0 20130714) is still complaining
sfinae.cpp:在结构 A"的实例化中:sfinae.cpp:19:11:
从这里需要 sfinae.cpp:9:5: 错误:
中没有名为type"的类型'struct std::enable_if'
A(int n) : val(n) {};
sfinae.cpp: In instantiation of 'struct A': sfinae.cpp:19:11:
required from here sfinae.cpp:9:5: error: no type named 'type' in
'struct std::enable_if'
A(int n) : val(n) {};
这样的事情对构造函数来说是可能的吗?这是否可以与另一个构造函数(复制构造函数和移动构造函数)一起使用?
Is something like this possible for constructor? Is this possible with another constructor(s) (copy-constructor and move-constructor)?
推荐答案
With C++20
您只需将 requires
添加到模板即可实现:
With C++20
You can achieve that simply by adding requires
to the template:
template <typename U = T> requires U::value
A(int n) : val(n) { }
requires
子句获取一个 常量表达式
,其计算结果为 true
或 false
> 因此决定是否在重载决议中考虑此方法,如果 requires 子句为真,否则忽略它.
The requires
clause gets a constant expression
that evaluates to true
or false
deciding thus whether to consider this method in the overload resolution, if the requires clause is true, or ignore it otherwise.
代码:https://godbolt.org/z/CKTDFE
相关文章