关于模板函数
  • 板块学术版
  • 楼主zhangbo1000
  • 当前回复12
  • 已保存回复13
  • 发布时间2024/6/13 13:58
  • 上次更新2024/6/13 19:14:56
查看原帖
关于模板函数
760291
zhangbo1000楼主2024/6/13 13:58

rt,众所周知,我们可以利用模板实现一种能接受任意个数参数的函数,如:

template<typename _Tp>
_Tp max(const _Tp& a,const _Tp& b){
	return a<b?b:a;
}
template<typename First_Tp,typename... Rest_Tp>
	First_Tp max(const First_Tp& first,const Rest_Tp&...rest){
	return max(first,max(rest...));
}

但是,以下写法不能通过编译:

template<typename Tp>
void output(Tp x){
	cout<<x;
}
template<typename...Tp>
void output(int x,Tp...y){
	output(x);
	output(y...);
}

以下写法又可以了:

template<typename Tp>
void output(Tp x){
	cout<<x;
}
template<typename otherTp,typename...Tp>
void output(otherTp x,Tp...y){
	output(x);
	output(y...);
}

这是为什么,是因为展开参数包的边界不能固定类型吗?还是什么别的?

2024/6/13 13:58
加载中...