Templates and Generic Programming
- 泛型技術(shù)扣唱。比如:模板技術(shù)汞舱,RTTI技術(shù)诸老,虛函數(shù)技術(shù)隆夯,要么是試圖做到在編譯時(shí)決議,要么試圖做到運(yùn)行時(shí)決議别伏。
- 模板是泛型編程的基礎(chǔ)
模板 template
- 模板不是類或函數(shù)蹄衷,可以將模板看作編譯器生成類或者函數(shù)的一份說明書;
- 編譯器根據(jù)模板創(chuàng)建類或者函數(shù)的過程稱為模板的實(shí)例化(instantiation);
- 使用模板時(shí),必須(隱式或顯式)指定模板實(shí)參
- 顯式模板實(shí)參(explicit template argument)
max<int> (1, 3.0); //function template Blob<int> a; //class template 必須顯式指定
- 隱式模板實(shí)參(implicit template argument)
max(1, 2); //function template
函數(shù)模板(function template)
template<template parameter list>
template<typename T1, typename T2>
函數(shù)模板實(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ù)的模板實(shí)參必須是常量表達(dá)式
cout << compare("a", "ba") << endl;
類模板(class template)
類模板的實(shí)例化
- 類模板實(shí)例化必須提供顯式模板實(shí)參
Blob<int> ia;
Blob<int> ia2 = {0, 1, 2, 3, 4};
- 一個(gè)實(shí)例化了的類模板厘肮,其成員函數(shù)只有在使用時(shí)才被實(shí)例化
Blob<int> ia2 = {0, 1, 2, 3, 4}; // 類模板實(shí)例化
ia2.size(); // 實(shí)例化 Blob<int>::size() const