简体   繁体   English

C ++:模板类专门化和类型特征

[英]C++ : template class specialization and type traits

My problem is the following 我的问题是以下

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 */
}

I want my template class to be compatible with std::string without reimplementing all the functions. 我希望我的模板类与std::string兼容,而无需重新实现所有功能。 For std::string I want min = "" and max = "" . 对于std :: string我想要min = ""max = "" Currently, it crashes as 0 for example cannot be converted to a string. 当前,它崩溃为0,例如无法将其转换为字符串。 How to do that ? 怎么做 ? (if I can specialize only the constructor and the main setter it would be great). (如果我只能专注于构造函数和主要的二传手,那就太好了)。

Create the wrapper I guess? 我想创建包装器吗? :

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 "";
}

You can always select the right overload for something to handle special cases with enable_if or you can think better about how to make your code more robust. 您始终可以使用enable_if为某些特殊情况选择正确的重载,或者可以更好地考虑如何使代码更健壮。 Using 0 to initialize a template parameter is not a good idea, while T() is. 使用0初始化模板参数不是一个好主意,而T()则是。

制作自己的numeric_limits ,该值将重定向到标准值并专门用于字符串。

set(T & const p_Arg = Initializer<T>())

其中Initializer专用于所有受支持的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM