【问题标题】:Accepting certain types in constructor [closed]在构造函数中接受某些类型[关闭]
【发布时间】:2011-06-18 07:10:15
【问题描述】:

作为this 问题的后续,如何更改代码以便我可以在类的构造函数中使用它?我正在编写一个新类,其中输入需要是某种数字,但仅此而已。然而,代码就像在函数前面声明类型一样。由于构造函数没有确切的类型,我需要它不要为函数本身声明类型

我的新班级:

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


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

};

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

【问题讨论】:

  • 您最好以一些代码的形式给出示例,让我们知道您究竟想要实现什么。
  • 这个问题不清楚,无法自信地回答。

标签: c++ class templates constructor


【解决方案1】:

我想你想限制构造函数模板的 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)
     {

     }
};

此构造函数模板只能接受is_arithmetic&lt;T&gt;::valuetrue 的那些Tenable_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)
     {

     }
};

此构造函数模板只能接受exists&lt;T,supported_types&gt;::valuetrue 的那些Texists 元函数检查 T 是否存在于类型列表 supported_types 中。您可以向此类型列表添加更多类型

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2017-10-14
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    相关资源
    最近更新 更多