c – 如何根据模板类型使用std :: enable_if启用或禁用构造函数?

前端之家收集整理的这篇文章主要介绍了c – 如何根据模板类型使用std :: enable_if启用或禁用构造函数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下模板对象: @H_403_2@template< typename type_1,typename type_2 > struct result { // I want to enable these two constructors only if type_1 != type_2 result( type_1 f ) : foo{f} {} result( type_2 b ) : bar{b} {} // I want to enable this constructor only if type_1 == type_2 result( type_1 f,type_2 b ) : foo{f},bar{b} {} // Other member functions removed. type_1 foo; type_2 bar; };

如何根据需要使用std :: enable_if启用或禁用构造函数

例如:

这个只有前两个构造函数

@H_403_2@result<string,int> // type_1 != type_2

这个只有第三个构造函数

@H_403_2@result<int,int> // type_1 == type_2

解决方法

This似乎有效,但我不确定它是最佳方式

因此,只需将具有默认值的新模板参数添加到构造函数以启用SFINAE

@H_403_2@#include <type_traits> template< typename type_1,typename type_2 > struct result { // I want to enable these two constructors only if type_1 != type_2 template<typename T1 = type_1,typename T2 = type_2> result( type_1 f,typename std::enable_if<!std::is_same<T1,T2>::value>::type * = nullptr ) : foo{f} {} template<typename T1 = type_1,typename T2 = type_2> result( type_2 b,T2>::value,int >::type * = nullptr ) : bar{b} {} /* ^^^ need this to avoid duplicated signature error with above one*/ // I want to enable this constructor only if type_1 == type_2 template<typename T1 = type_1,type_2 b,typename std::enable_if<std::is_same<T1,T2>::value>::type * = nullptr ) : foo{f},bar{b} {} type_1 foo; type_2 bar; }; int main() { result<int,double> r(1); result<int,double> r2(1.0); result<int,int> r3(1,2); // disbaled //result<int,double> r4(1,2.0); //result<int,int> r5(1); }

另请阅读:Select class constructor using enable_if

猜你在找的C&C++相关文章