stl学习之模板

模板是实现代码重用机制的一种工具,实质就是实现类型参数化,即把类型定义为参数。
C++提供两种模板:函数模板,类模板。
 
template<typename T>     //或者  template<class T>
T my_max(T a, T b)
{
    return a>b ? a : b;
}

template<typename T>     //或者   template<class T>
class CMax
{
public:
    CMax(T a, T b)
    {
        m_a = a;
        m_b = b;
    }
    T GetMax()
    {
        return m_a > m_b ? m_a : m_b;
    }
private:
    T m_a;
    T m_b;
};

int _tmain(int argc, _TCHAR* argv[])
{
    int iMax = my_max(3, 5);
    char chMax = my_max('w', 'd');
    float fMax = my_max(2.7f, 1.3f);

    CMax<int> maxInt(3, 5);//需要指定类型
    int iMax2 = maxInt.GetMax();

    CMax<char> maxChar('w', 'd');
    char chMax2 = maxChar.GetMax();

    CMax<float> maxFloat(2.7f, 1.3f);
    float fMax2 = maxFloat.GetMax();

    return 0;
}

可以定义多种类型的形参。
template<typename T1, typename T2>
class CTest
{...};
对象实例化时:
CTest testA<int, float>;
CTest testB<double, string>

函数模板就是建立一个通用的函数,其函数返回类型和形参类型不具体指定,而是用虚拟的类型来代表。
凡是函数体相同的函数都可以用函数模板来代替,不必定义多个函数,只需在模板中定义一次即可。
在调用函数时系统会根据实参的类型来取代模板中的虚拟类型,从而实现了不同函数的功能。

原文地址:https://www.cnblogs.com/ultracpp/p/4099502.html