Cherno 视频:https://www.youtube.com/watch?v=I-hZkUa9mIs&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb&index=53
template 编译:http://www.voidcn.com/article/p-yvuewxdj-ws.html
template will be evaluated in compile time
Function template
the template function Print() only gets created when we call it
#include<iostream>
#include<string>
template<typename T>
void Print(T value){
std::cout<< value<<std::endl;
}
int main(int argc, char const *argv[])
{
Print(5);
Print("Hello");
Print(5.5f);
std::cin.get();
return 0;
}
同样,我们 也可以指定输入template的类型,比如:
Print<int>(5);
template 在我们调用之前是不会被编译的!!
template doesn't really exist until we call it
当我们调用一个函数模板时,编译器会根据函数实参来推断模板的具体类型,然后根据这个类型实例化这个类型的版本函数。
当编译器遇到一个template时,不能够立马为他产生机器代码,它必须等到template被指定某种类型。也就是说,函数模板和类模板的完整定义将出现在template被使用的每一个角落,比如遇到上述中的3个Print()语句时,才能确定编译内容,否则编译器没有足够的信息产生机器代码。
Class template
#include<iostream>
#include<string>
#define LOG(x) std::cout<<x<<std::endl;
template<int N>
class Array
{
public:
int GetSize() { return N; }
private:
int m_Array[N];
};
int main(int argc, char const *argv[])
{
Array<5> a;
LOG(a.GetSize())
std::cin.get();
return 0;
}
Note:
int m_Array[N] is a stack allocated array! --> N has to be konwn at compile
time! --->also template are evaluated at compile time!!