当前位置:网站首页>Variable parameter expression

Variable parameter expression

2022-06-11 13:30:00 Hair like snow ty

There is a template function as follows

template<typename...T>
auto print_result(T... args)
{
    
	(cout << ... << args) << " end " << endl;
	return (... + args);
}

int main()
{
    
	cout << print_result(10, 20, 30, 40) << endl;
	system("pause");
	return 0;
}

result :
 Insert picture description here
Now there is a need , You want the value of each parameter to expand the original 2 times , Then we add each other . To solve this problem , A better way is to introduce an intermediate function template , as follows :

template<typename...T>
auto print_calc(T... args)
{
    
	return print_result(2 * args ...);
}

In the above example 2args… This way of writing , It's actually a variable parameter expression , Equivalent to print_result(210,220,230,2*40);

int main()
{
    
	cout << print_result(10, 20, 30, 40) << endl;
	cout << print_calc(10, 20, 30, 40) << endl;
	system("pause");
	return 0;
}

result :
 Insert picture description here

原网站

版权声明
本文为[Hair like snow ty]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111325091373.html