C++ 函数模版 不定参数

实现参数不固定的加法,需要如下实现


template<typename T>  
T tempSum(const T& t)
{
	static T sum;
	sum += t;
	return sum;
}
//这里保存计算结果
template<typename T>  
T saveValue(const T& t)
{
	static T temp = t; //这里必须用static的功能
	return temp;
}
 
void temAdd() {}   //递归结束条件
template<typename T,typename... U>
T temAdd(const T& first, const U&... args)
{
	T result = tempSum(first);   //思考为什么用另外的函数计算,而不是定义static变量在次数计算
	temAdd(args...);             //递归,(这也是为什么要把结果保存在另一个函数的原因)
	return saveValue(result);	 //思考这里为什么要用一个函数保存结果
}
 
int main()
{
	//cout << temAdd("a", "bc", "ed") << endl; //错误 char *不能用+运算符进行运算
	cout << temAdd(string("a"),string("bc"),string("ed")) << endl;
	cout << temAdd(1,3,5,7,9) << endl;
 
	return 0;
}

上面问题的答复:

saveValue 这个函数里面有对一个static 变量进行定义,但是对静态变量的定义只能定义一次,之后其实是没有生效的。因为静态变量的定义其实是编译时期,而不是运行时期,否则运行时候的链接会出错。那么那个变量的初次定义其实就是最终的答案。

posted @ 2023-08-22 14:08  wsl-hitsz  阅读(87)  评论(0编辑  收藏  举报