Templates and Generic Programming
- 泛型技術(shù)。比如:模板技術(shù),RTTI技術(shù)蓬推,虛函數(shù)技術(shù),要么是試圖做到在編譯時決議澡腾,要么試圖做到運行時決議拳氢。
- 模板是泛型編程的基礎(chǔ)
模板 template
- 模板不是類或函數(shù),可以將模板看作編譯器生成類或者函數(shù)的一份說明書;
- 編譯器根據(jù)模板創(chuàng)建類或者函數(shù)的過程稱為模板的實例化(instantiation);
- 使用模板時蛋铆,必須(隱式或顯式)指定模板實參
- 顯式模板實參(explicit template argument)
max<int> (1, 3.0); //function template Blob<int> a; //class template 必須顯式指定
- 隱式模板實參(implicit template argument)
max(1, 2); //function template
函數(shù)模板(function template)
template<template parameter list>
template<typename T1, typename T2>
函數(shù)模板實例化 instantiate
When the compiler instantiates a template, it creates a new “instance” of
the template using the actual template argument(s) in place of the
corresponding template parameter(s).
非類型模板參數(shù)(nontype parameter)
template <unsigned N, unsigned M>
inline int compare(const char (&p1)[N], const char (&p2)[M]) {
return strcmp(p1, p2);
};
// 非類型模板參數(shù)的模板實參必須是常量表達式
cout << compare("a", "ba") << endl;
類模板(class template)
類模板的實例化
- 類模板實例化必須提供顯式模板實參
Blob<int> ia;
Blob<int> ia2 = {0, 1, 2, 3, 4};
- 一個實例化了的類模板馋评,其成員函數(shù)只有在使用時才被實例化
Blob<int> ia2 = {0, 1, 2, 3, 4}; // 類模板實例化
ia2.size(); // 實例化 Blob<int>::size() const
container
順序容器 sequential container
vector
deque
list
forward_list
array
string