c++ - 在构造函数中接受某些类型

标签 c++ class templates constructor

<分区>

作为 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>::valuetrue . 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>::valuetrue . exists元函数检查是否 T存在于类型列表中 supported_types或没有。您可以向此类型列表添加更多类型

并执行typelist , 和 exists在这里(见我的解决方案):

关于c++ - 在构造函数中接受某些类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394465/

相关文章:

javascript - 使用带 Angular js 的灰尘模板

c++ - std::bind 应该需要移动构造函数吗?

c++ - C 和 C++ 中的字符

c++ - 为什么 std::less<int>() 是函数对象

c++ - 我可以禁用 SFINAE 吗?

class - 在 Python 中制定动态类

java - 如何在实现 Parcelable 的类中使用 transient 变量?

java - 是否可以在 Gradle 中创建原型(prototype)?

class - Apex 触发器测试类 - 新手指南

c++ - 如何为输入和输出参数使用单独的参数包?