模板函数

template<typename T>

//声明和实现在一起
T const& Max(T const& a, T const& b)
{
    return a > b ? a : b;
}
//必须再次声明
template<typename T> 
void show(T const& a)
{
    cout << a << endl;
}
 
#include "ctemplate.h"
int _tmain(int argc, _TCHAR* argv[])
{
    string str1 = "abc";
    string str2 = "acd";
    cout << Max(1,2) << endl;
    cout << Max(str1, str2) << endl;
    cout << Max<char>(3, 'a') << endl;
    cout << Max<double>(3.4, 3.5) << endl;
    
    show("aa");
}

成员函数模板,类的成员函数也可以定义为模板

class Printer {
public:
    template<typename T>
     void print(const T& t) {
         cout << t <<endl;
     }
 };
 
Printer p;
p.print<const char*>("abc");
//打印abc
原文地址:https://www.cnblogs.com/osbreak/p/9224339.html