C ++:模板类特化和类型特征(C++ : template class specialization and type traits)

我的问题如下

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,例如无法转换为字符串。 怎么做 ? (如果我只能专门构造构造函数和主要的setter那就太棒了)。

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. For std::string I want min = "" and max = "". Currently, it crashes as 0 for example cannot be converted to a string. How to do that ? (if I can specialize only the constructor and the main setter it would be great).

最满意答案

我想创建包装器? :

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

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

更多推荐