
上QQ阅读APP看书,第一时间看更新
How to do it...
Let's implement a function that takes arbitrarily many parameters and returns their sum:
- At first, we define its signature:
template <typename ... Ts>
auto sum(Ts ... ts);
- So, we have a parameter pack ts now, and the function should expand all the parameters and sum them together using a fold expression. If we use any operator (+, in this example) together with ... in order to apply it to all the values of a parameter pack, we need to surround the expression with parentheses:
template <typename ... Ts>
auto sum(Ts ... ts)
{
return (ts + ...);
}
- We can now call it this way:
int the_sum {sum(1, 2, 3, 4, 5)}; // Value: 15
- It does not only work with int types; we can call it with any type that just implements the + operator, such as std::string:
std::string a {"Hello "};
std::string b {"World"};
std::cout << sum(a, b) << '\n'; // Output: Hello World