c++ primer学习之--------模板
2011-02-22 11:15
141 查看
模板定义以关键字template开始,后接模板形参表,模板形参表是用尖括号扩住的一个或多个模板形参的列表,形参之间以逗号分隔。
模板形参表不能为空。
模板形参可以是表示类型的类型形参,也可以是表示常量表达式的非类型形参。类型形参跟在关键字class或typename之后定义。在函数模板形参表中,class和typename的意义是一样的,都指出后面所接的名字表示一个类型。
如果是类型形参,该形参表示未知类型,如果是非类型形参,它是一个未知值。
1. inline函数模板
说明符放在模板形参表之后、返回类型之前,不能放在关键字template之前。
template <typename T> inline T min(const T&, const T&); //ok
inline template <typename T> T min(const T&, const T&); //error
2. 类模板
template <class Type> class Queue {
public:
Queue();
Type &front(); //return element from head of Queue
const Type &front() const;
void push(const Type &); //add element from head of Queue
void pop(); //remove element from head of Queue
bool empty() const; // true if no elements in the Queue
private:
};
使用类模板时,必须为模板形参显示指定实参:
Queue<int> qi; //queue that holds ints
Queue< vector<double> > qc; //queue that holds vectors of doubles
Queue<string> qs; //queue that holds strings
模板形参表不能为空。
模板形参可以是表示类型的类型形参,也可以是表示常量表达式的非类型形参。类型形参跟在关键字class或typename之后定义。在函数模板形参表中,class和typename的意义是一样的,都指出后面所接的名字表示一个类型。
如果是类型形参,该形参表示未知类型,如果是非类型形参,它是一个未知值。
1. inline函数模板
说明符放在模板形参表之后、返回类型之前,不能放在关键字template之前。
template <typename T> inline T min(const T&, const T&); //ok
inline template <typename T> T min(const T&, const T&); //error
2. 类模板
template <class Type> class Queue {
public:
Queue();
Type &front(); //return element from head of Queue
const Type &front() const;
void push(const Type &); //add element from head of Queue
void pop(); //remove element from head of Queue
bool empty() const; // true if no elements in the Queue
private:
};
使用类模板时,必须为模板形参显示指定实参:
Queue<int> qi; //queue that holds ints
Queue< vector<double> > qc; //queue that holds vectors of doubles
Queue<string> qs; //queue that holds strings
相关文章推荐
- C++ Primer 学习笔记_84_模板与泛型编程 -模板特化
- C++ Primer复习和学习笔记 第十六章 模板与泛型编程
- C++ Primer 学习笔记_85_模板与泛型编程 -模板特化[续]
- C++ Primer 学习笔记十六 —— 模板与泛型编程
- C++ Primer 学习笔记_83_模板与泛型编程 --一个泛型句柄类
- C++ Primer 学习笔记_86_模板与泛型编程 -满载与函数模板
- C++ Primer 学习笔记_75_模板与泛型编程 --模板定义
- C++ Primer 学习笔记_84_模板与泛型编程 --模板特化
- C++ Primer 学习笔记_75_模板与泛型编程 -模板定义
- C++ Primer 学习笔记_76_模板与泛型编程 -模板定义[续]
- C++ Primer 学习笔记_77_模板与泛型编程 --实例化
- C++ Primer 第16章 模板与泛型编程 学习笔记
- C++ Primer 学习笔记_77_模板与泛型编程 -实例化
- c++ primer 学习笔记13--模板
- C++ Primer 学习笔记_79_模板与泛型编程 --模板编译模型
- C++ Primer 学习笔记_78_模板与泛型编程 -实例化[续]
- C++ Primer 学习笔记_76_模板与泛型编程 --模板定义[续]
- C++ Primer 学习笔记_76_模板和泛型编程 --模板定义[继续]
- 12.29--C++模板与泛型编程--《C++ Primer》学习
- C++ Primer 学习笔记_79_模板与泛型编程 -模板编译模型