以表达式作为template参数

目录

一.template参数的分类:

二.非类型参数与默认参数值一起使用

三.应用


一.template参数的分类:

①.某种类型:

template<typename T>;

②.表达式(非类型):

template<int length,int position>;

其中length和position在编译时就已经确定为常量表达式。

非类型模板参数在编译期间就已经实例化,所以其模板实参必须是常量表达式。

二.非类型参数与默认参数值一起使用

 template的参数中也可以设置默认参数,其设置规则和在函数中设置默认参数类似。

示例:

template<int a,int b=10>;

三.应用

利用非类型参数设置的template函数:


template<int length,int position=1>
void display_find(const vector<int>&vec)
{
	for (int i = 0; i < length; i++)
	{
		cout << vec[i] << " ";
	}
	cout << endl;
	cout << "第" << position << "位数是:" << vec[position-1] << endl;
}

调用过程:

 ①.只给模板函数传入一个模板参数值

int main()
{
	int arr[8] = { 1,5,8,9,10,2,6,7 };
	vector<int>vec(arr, arr + 8);
	display_find<8>(vec);


	system("pause");
	return 0;
}

程序运行结果:

此时模板函数第二个参数为默认值1。

 ②.给模板函数传入两个模板参数值

int main()
{
	int arr[8] = { 1,5,8,9,10,2,6,7 };
	vector<int>vec(arr, arr + 8);
	//display_find<8>(vec);

	display_find<8, 5>(vec);

	system("pause");
	return 0;
}

程序运行结果:

此时传入的第二个参数值5代替模板函数的第二个默认参数值。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值