所謂模板函數其實就是建立一個通用函數,這個通用函數的形參類型不具體指定,用一個虛擬類型來代表,這個通用函數就被稱為函數模板。
例:
#include <iostream> using namespace std; class A { public: template<typename T> void display(T temp); template<typename T> A(T temp); };
template<typename T> void A::display(T temp) { cout<<temp<<endl; }
template<typename T> A::A(T temp) { cout<<temp<<endl; }
template <typename T> void test(T temp) { cout<<temp<<endl; } void main() {
test<int>(12); //普通模板函數,在VS2013下測試,其實加不加后面的<int>都可 A aa(12); //請注意這一行 aa.display<int>(15); //成員函數是模板函數 }