c++模板与泛型编程基础

(1)定义函数模板(function template

函数模板是一个独立于类型的函数,可以产生函数的特定类型版本。

复制代码
// implement strcmp-like generic compare function
template <typename T>
int compare(const T &v1, const T &v2)
{
    if (v1 < v2) return -1;
    if (v2 < v1) return 1;
    return 0;
}
复制代码

模板定义以关键字template开始,后接尖括号括住的模板形参表。

模板形参可以是表示类型的类型形参(type parameter),也可以是表示常量表达式的非类型形参(nontype parameter)。上面程序中的T是类型形参。

// compiler instantiates int compare(const int&, const int&)
cout << compare(1, 0) << endl;
// compiler instantiates int compare(const string&, const string&)
string s1 = “hi”, s2 = “world”;
cout << compare(s1, s2) << endl;

使用函数模板时,编译器会将模板实参绑定到模板形参。编译器将确定用什么类型代替每个类型形参,用什么值代替每个非类型形参,然后产生并编译(称为实例化)该版本的函数。

上面的例子中,编译器用int代替T创建第一个版本,用string代替T创建第二个版本。

函数模版不支持返回值

(2)定义类模板(class template

在定义的类模板中,使用模板形参作为类型或值的占位符,在使用类时再提供具体的类型或值

复制代码
template <typename Type> 
class Queue
{
public:
    Queue();
    Type & front();
    const Type & front() const;
    void push(const Type &);
    void pop();
    bool empty() const;
private:
    // …
};
复制代码

与调用函数模板不同,使用类模板时,必须为模板形参显示指定实参

Queue<int> qi; // Queue that holds ints
Queue<string> qs; // Queue that holds strings
原文地址:https://www.cnblogs.com/raichen/p/5808512.html