作为 this 的跟进问题,如何更改代码以便我可以在类的构造函数中使用它?我正在编写一个新类,其中输入需要是某种数字,但别无其他。但是,代码就像在函数前面声明类型一样。由于构造函数没有确切的类型,我需要它不为函数本身声明类型
我的新类(class):
class C{
public:
C();
C(T value);// specifically looking for this
T f(T value); // what the code currently does
};
链接中的代码创建了一个[接受并]返回整数类型 T
的函数。我需要它完全不返回任何东西,以便它可以与构造函数一起使用
我想你想限制构造函数模板的类型。如果是这样,那么您可以这样做:
#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)
{
}
};
这个构造函数模板只能接受那些T
为此 is_arithmetic<T>::value
是true
. enable_if
的执行与 the other answer 中给出的完全相同.
或者,如果您没有 type_traits
, 那么你可以使用 typelist
连同 enable_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)
{
}
};
这个构造函数模板只能接受那些T
为此 exists<T,supported_types>::value
是true
. exists
元函数检查是否 T
存在于类型列表中 supported_types
或没有。您可以向此类型列表添加更多类型。
并执行typelist
, 和 exists
在这里(见我的解决方案):