2012-07-22 108 views
2

我的问题是下面C++:模板类专业化和类型性状

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,它会很棒)。

+0

兼容你的意思是:如果'T == std :: string'应该可以很好地播放,或者'MyClass'应该是'std :: string'的嵌入替代品? – pmr 2012-07-22 17:55:37

回答

3

创建包装我猜? :

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

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

1

制作您自己的numeric_limits重定向到标准的和专门为字符串。

+0

如果你把它叫做'default_max'什么的,它会更容易。 :-) – 2012-07-22 18:08:28

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

其中Initializer是专门为所有支持的类型。