【问题标题】:How to accept only numbers and strings in templates in C++11?如何在 C++11 的模板中只接受数字和字符串?
【发布时间】:2018-04-02 03:37:34
【问题描述】:

正如标题所说,在 C++11 中,我如何声明一个只接受数字(intlongfloatdouble)和字符串的模板?

template<typename T>
class CustomClass {
    public:
        T data;
};

【问题讨论】:

    标签: c++ c++11 templates sfinae template-specialization


    【解决方案1】:

    把它放在类定义的任何地方:

    static_assert(std::is_arithmetic<T>::value ||
                  std::is_same<T, std::string>::value,
                  "Wrong argument type");
    

    根据口味调整条件。

    【讨论】:

      【解决方案2】:

      例如,使用模板偏特化和模板默认值。

      有点像

      template <typename T, bool =    std::is_arithmetic<T>::value
                                   || std::is_same<T, std::string>::value>
      class CustomClass;
      
      template <typename T>
      class CustomClass<T, true>
       {
         public:
            T data;
       };
      

      所以你可以拥有

      CustomClass<int>  cci;
      CustomClass<std::string>  ccs;
      // CustomClass<std::istringstream>  cciss; // compilation error
      

      【讨论】:

        猜你喜欢
        • 2012-11-23
        • 2013-06-03
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 2011-06-09
        • 2016-06-08
        • 2015-04-30
        相关资源
        最近更新 更多