2012-07-22 75 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是專門爲所有支持的類型。