函数模版实例化

#include <iostream>
using namespace std;
template<typename T,typename D>
auto decrease(T x, D y) {
	return (x - y);
}
//auto是根据return的语句来推断auto的类型
int main() {
	cout <<  decrease(5.0, 3) << endl;
	return 0;
}

//Explicit instantiation(显式实例化)
//强制某些函数实例化,可出现于程序中模板定义后的任何位置。
template < typename T >
void f(T s) {
	std::cout << s << '\n';
}
template void f<double>(double); // 实例化,编译器生成代码
								//  void f(double s) {   // T: double
							   //      std::cout << s << '\n';
							   // 
template void f<>(char);    // 实例化 f<char>(char) ,推导出模板实参
template void f(int);        // 实例化 f<int>(int) ,推导出模板实参

//Implicit instantiation(隐式实例化)
//编译器查看函数调用,推断模版实参,实现隐式实例化。
#include <iostream>
template<typename T>
void f(T s) {
	std::cout << s << '\n';
}
int main() {
	f<double>(1); // 实例化并调用 f<double>(double)
	f<>('a'); // 实例化并调用 f<char>(char)
	f(7); // 实例化并调用 f<int>(int)
	void (*ptr)(std::string) = f; // 实例化 f<string>(string)
}

//Instantiated function / class (实例函数 / 实例类)
/*A function instantiated from a function template is called an instantiated function.
A class instantiated from a class template is called an instantiated class.*/
//(由函数模板实例化得到的函数叫做“实例函数”,由类模板实例化得到的类叫做“实例类”)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值