Essential C++ 笔记 - 第三章泛型编程风格
一、模板
// 函数模板
// 定义
template <typename T1, typename T2>
T1 test(T2 t) {
// ...
}
// 调用
float ret = test(10);
// 定义
template <int Value>
int test() {
int ret = Value;
return ret;
}
// 调用
int ret = test<10>();
// 类模板
// 定义
template <typename T>
class test {
private:
T t;
public:
void show(T t1);
};
template <typename T>
void test::show(T t1){
// ...
}
// 调用
test<int> t;
template 与 template 一般情况下是通用的。但是,当T是一个类,而这个类又有子类时,应该使用 template
// typename T::innerClass myInnerObject;
// 这里的typename告诉编译器,T::innerClass是一个类,程序要声明一个T::innerClass类的对象,而不是声明T的静态成员。
二、容器
1、序列式容器( Sequential Container )
序列式容器用来维护一组排列有序、型别相同的元素。
#include <vector>
#include <list>
#include <deque>
using namespace std;
// 产生空的容器
list<string> slist;
vector<int>