接受构造函数中的某些类型

时间:2011-06-18 07:10:16

标签: c++ class templates constructor

作为this问题的后续问题,如何更改代码以便我可以在类的构造函数中使用它?我正在写一个新的类,其中输入需要是某种类型的数字,但没有别的。但是,代码就像在函数前面声明类型一样。因为构造函数不完全具有类型,所以我需要它不为函数本身声明类型

我的新课程:

class C{
     public:
         C();
         C(T value);// specifically looking for this


         T f(T value); // what the code currently does

};

链接中的代码创建一个[接受并且]返回整数类型T的函数。我需要它不返回任何东西,以便它可以与构造函数一起使用

1 个答案:

答案 0 :(得分:3)

我认为你想限制构造函数模板的 types 。如果是这样,那么你可以这样做:

#include <type_traits>
//#include <tr1/type_traits> // for C++03, use std::tr1::

class C
{
  public:

     template<typename T>
     C(T value, typename enable_if<std::is_arithmetic<T>::value,T>::type *p=0)
     {

     }
};

此构造函数模板只能接受Tis_arithmetic<T>::value的{​​{1}}个trueenable_if的实现完全相同,如the other answer中所述。


或者,如果您没有type_traits,则可以使用typelistenable_if。我认为这是一个更好的解决方案,因为您可以专门定义支持的类型列表。

typedef typelist<int> t1;
typedef typelist<short, t1> t2;
typedef typelist<char, t2> t3;
typedef typelist<unsigned char, t3> t4;
//and so on

typedef t4 supported_types;//supported_types: int, short, char, unsigned char

class C
{
  public:

     template<typename T>
     C(T value, typename enable_if<exits<T,supported_types>::value,T>::type *p=0)
     {

     }
};

此构造函数模板只能接受Texists<T,supported_types>::value的{​​{1}}个trueexists元函数检查类型列表T中是否存在supported_types或否。您可以向此类型列表添加更多类型

typelistexists的实施就在这里(参见我的解决方案):