2017-06-01 17 views
-1

我有一個類模板,當類型是一個整數時,我想要做些什麼,當它是一個字符串和雙精度時,做其他事情。我該怎麼做?我有這樣的方法:C++ If-與模板中的類型

template <typename T> class abc{ 
    void method(T i) 
    { 
     if(i is a string) 
      do sth 
     else if(i is an integer) 
      do sth else 
     else if(i is a double) 
      do sth else else 
    } 
} 
+1

似乎更像你需要*重載*比模板。或者可能是模板專業化。 –

+0

你到底想要做什麼? – syntagma

+0

我想做一個列表,我可以比較一個> b,當涉及到整數和雙精度,但我不能用字符串 – jakub1998

回答

2

您可以使用模板專門化。

template<typename T> 
class A { 
    void method(T); 
}; 

你定義的類型的特想要

template<> void A<int>::method(int) {} 
template<> void A<string>::method(string) {} 
template<> void A<float>::method(float) {} 

我沒有測試此代碼,但你可以在這裏找到更多的信息http://en.cppreference.com/w/cpp/language/template_specialization

+0

你不應該[專門模板](http://www.gotw.ca/publications/mill17.htm) – nefas

0
template <typename T> 
void method(T i){ 
if(typeid(i) == typeid(string)){ 
cout << "string" <<endl; 
}else if(typeid(i) == typeid(int)){ 
cout << "int" <<endl; 
}else{ 
///... 
} 
} 

int main() { 

string a = ""; 
method(a); 
return 0; 

}

,你應該包括:

#include <typeinfo> 
+0

code只有答案不好,格式錯誤的代碼只有答案更糟糕。最重要的是,這不會幫助 – user463035818

1

我希望做一個列表,當它涉及到整數和雙精度我可以比較a > b,但我不能用繩子做到這一點 - jakub1998

作爲的問題事實上,你可以比較字符串。但在一般情況下,你可以模仿什麼std::map的確,走在第二個模板參數是訂購2 T個政策:

template <typename T, typename Compare = std::greater<T>> 
class abc { 
    void method(T i, T j) 
    { 
     if(Compare{}(i, j)) { 
      // ... 
     } 
    } 
}; 

注意默認參數std::greater,這回退到調用i > j如果用戶不提供自定義比較器。