如何根据模板类型使用std :: enable_if启用或禁用构造函数? [英] How do I use std::enable_if to enable or disable constructors depending on template types?

查看:276
本文介绍了如何根据模板类型使用std :: enable_if启用或禁用构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模板对象:

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 启用或禁用所需的构造函数?

How do I use std::enable_if to enable or disable the constructors as required?

例如:

该对象只有前两个构造函数:

This one would have only the first two constructors:

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

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

This one would have only the third constructor:

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


推荐答案

似乎可行,但我不确定这是最佳方法

This seems working, but I am not sure it is the optimal way

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

So just add new template parameters with default values to the constructor to enable 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, 
           typename std::enable_if<!std::is_same<T1, 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, typename T2 = type_2>
    result( type_1 f, 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);
}

也请阅读:使用enable_if

这篇关于如何根据模板类型使用std :: enable_if启用或禁用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆