Cherno c++ learning -- template

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!! 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值