加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:41:01 所属栏目:百科 来源:网络整理
导读:我有以下模板对象: 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 construct
我有以下模板对象:
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启用或禁用构造函数?

例如:

这个只有前两个构造函数:

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

这个只有第三个构造函数:

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

解决方法

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

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

#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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读