C++标准库 02 模板template用法总结

发布于 2021-06-07  49 次阅读


引言

  模板(Template)指C++程序设计设计语言中采用类型作为参数的程序设计,支持通用程序设计。C++ 的标准库提供许多有用的函数大多结合了模板的观念,如STL以及IO Stream。

一、函数模板

  函数模板能够使一个函数处理多种不同传入类型。
  函数模板声明如下:

template <class identifier> function_declaration;
template <typename identifier> function_declaration;

  下面来看一个swap函数的实例。

#include <iostream>
using namespace std;

template<typename T>void Tswap(T& a, T& b)
{
    T temp = a;
    a = b;
    b = temp;
}

int main()
{  
    int a{ 5 }, b{ 1 };
    Tswap(a, b);
    cout << a << ' ' << b << endl;
    string c{ "hello" }, d{ "world" };
    Tswap(c, d);
    cout << c << ' ' << d << endl;
    //display:
    //1 5
    //world hello
    return 0;
}

二、模板类

  下面试着来写一个简单的模板类。

#include <iostream>
using namespace std;

template<class T>class MyClass
{
private:
    T m_element;
public:
    //构造函数:
    MyClass(const T& _t = T{}) :m_element{ _t } { }

    void Show()
    {
        cout << "call func_show" << endl;
    }
};

int main()
{  
    MyClass<string> a;
    a.Show();
    MyClass<int> b{ 1 };
    b.Show();
    return 0;
}

三、模板专门化(将模板函数特化)

  当我们在处理一些问题时,模板可能会出现类型不匹配(如char*),这时候我们就需要单独书写一遍模板用来处理特殊问题。
  下面通过compare类来演示。

#include <iostream>
using namespace std;

template<class T>class compare
{
public:
    bool comp(const T& a, const T& b)
    {
        return a < b;
    }
};

template<>class compare<char*>
{
public:
    bool comp(const char* a, const char* b)
    {
        return a < b;
    }
};

int main()
{  
    compare<char*> c1;
    cout << c1.comp("hello", "world") << endl;
    //error without compare<char*>
    return 0;
}

四、模板类型转换

  还是上面的MyClass类,我们试着对他进行类型转换。

#include <iostream>
using namespace std;

class Base
{

};

class Derived : public Base
{

};

template<class T>class MyClass
{
private:
    T m_element;
public:
    MyClass(const T& _t = T{}) :m_element{ _t } { }

    void Show()
    {
        cout << "call func_show" << endl;
    }

    //类型转换
    template<class Tother> operator MyClass<Tother>()
    {
        cout << "Type conversion" << endl;
        MyClass<Tother> temp;
        //需要的语句
        return temp;
    }
};

int main()
{
    MyClass<Base> a;
    MyClass<Derived> b;
    a = b;
    return 0;
}

  注意:其中语句必须要是合理的,否则编译器将报错。

五、其他

  一个类没有模板,但它的成员有模板,这是合法的。

#include <iostream>
using namespace std;

class Util
{
public:
    template <class T> bool equal(T t1, T t2)
    {
        return t1 == t2;
    }
};

int main()
{
    Util util;
    util.equal<int>(1, 2);
    return 0;
}