【问题标题】:C++ : template class specialization and type traitsC++:模板类特化和类型特征
【发布时间】:2012-07-22 17:47:42
【问题描述】:

我的问题如下

template<class T> MyClass
{
    MyClass(/* Lots of parameters with no problem */, const T& min = 0, const T& max = std::numeric_limits<T>::max());
    set(/* Lots of parameters with no problem */, const T& min = 0, const T& max = std::numeric_limits<T>::max());
    /* Lots of function with no problem */
}

我希望我的模板类与std::string 兼容,而无需重新实现所有功能。对于 std::string 我想要min = ""max = ""。目前,它崩溃为 0 例如不能转换为字符串。怎么做 ? (如果我只能专门化构造函数和主设置器,那就太好了)。

【问题讨论】:

  • 兼容的意思是:如果T == std::string 应该很好玩,或者MyClass 应该是std::string 的直接替代品?

标签: c++ class templates specialization


【解决方案1】:

我猜是创建包装器? :

template<typename T> struct ttraits
{
static T max(){
return std::numeric_limits<T>::max();
}
static T min(){
return std::numeric_limits<T>::min();
}
};

template<> struct ttraits<std::string>
{
static std::string max(){
return ""; //or whatever max is for you
}
static std::string min(){
return "";
}

【讨论】:

    【解决方案2】:

    您始终可以使用enable_if 为某些特殊情况选择正确的重载,或者您可以更好地考虑如何使您的代码更健壮。使用0 初始化模板参数不是一个好主意,而T() 是。

    【讨论】:

      【解决方案3】:

      制作你自己的numeric_limits,它会重定向到标准的numeric_limits,专门用于字符串。

      【讨论】:

      • 如果你叫它default_max什么的,会更容易。 :-)
      【解决方案4】:
      set(T & const p_Arg = Initializer<T>())
      

      Initializer 专门用于所有支持的类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2017-07-18
        • 1970-01-01
        • 2012-08-28
        • 1970-01-01
        相关资源
        最近更新 更多