C++:舉例說明如何使用enable_if和模板的函式指標引數
阿新 • • 發佈:2018-10-31
下面的這個例子主要實現如下功能:
- 當引數為資料型別時,呼叫std::to_string()方法將數值轉化為字串並輸出。
- 當引數為std::string型別時,直接使用std::string的值輸出。
- 當引數為物件時,如果物件中含有std::string str()方法,則呼叫物件的std::string str()方法;
- 如果物件不含std::string str()方法,則返回空字串。
class Box { public: string str() { return "yes"; } }; class Bin { public: string str1() { return "no"; } }; template<typename T> std::string str(T& t) { cout << "1.---------------------" << endl; return "null"; }; template<> std::string str(string& t) { cout << "2.---------------------" << endl; return t; }; template<typename T, string (T::*U)() = &T::str> string str(typename std::enable_if<std::is_class<T>::value && !std::is_same<T, string>::value, T>::type& t) { cout << "3.---------------------" << endl; return t.str(); }; template<typename T> string str(typename std::enable_if<std::is_arithmetic<T>::value, T>::type& t) { cout << "4.---------------------" << endl; return std::to_string(t); }; int main() { string s = "sddds"; cout << str<string>(s) << endl; bool j = true; cout << str<bool>(j) << endl; int i = 1000; cout << str<int>(i) << endl; float f = 10.6f; cout << str<float>(f) << endl; Box b1; cout << str<Box>(b1) << endl; Bin b2; cout << str<Bin>(b2) << endl; return 1; }
2.---------------------
sddds
4.---------------------
1
4.---------------------
1000
4.---------------------
10.600000
3.---------------------
yes
1.---------------------
null
先看一下上述程式碼中使用的std::enable_if
typename std::enable_if<std::is_arithmetic<T>::value, T>::type
表示如果T是數值型別,則使用T的型別
typename std::enable_if<std::is_class<T>::value && !std::is_same<T, string>::value, T>::type
表示如果T是類,並且T不是string型別,則使用T的型別
再看下模板的函式指標引數
template<typename T, string (T::*U)() = &T::str>
表示如果要使用此模板函式,則T必須含有std::string str()函式
參考文件