Let's say I have a function sum
that takes a variadic parameter pack.
This function needs to ADD UP all of the parameters of the parameter pack using the operator +
.
NOTE: It CANNOT use the operator +=
in any way and can use only operator +
(as the program CANNOT assume that all parameters have operator+=
overloaded).
Then, function sum
needs to return the whole "sum" or accumulative add-up.
Here is the basic structure of what it would look like:
template <class... Args>
auto sum(Args... args)
{
// ... The code
}
NOTE: All arguments may not be of the same type AND you can assume that a corresponding overload of the operator+
exists for all types of the parameter pack.
It may be helpful to know that I am using C++ 20.
Use C++17's fold expressions, https://en.cppreference.com/w/cpp/language/fold. You don't need to specify the return type in most cases.
#include<cassert>
template <class... Args>
auto sum(Args... args) { // or right_fold_plus
return (args + ...);
}
int main() {
auto s = sum(1, 2, 3);
assert( s == 1 + 2 + 3 );
}
https://godbolt.org/z/1Yh118ETb
NOTE: It is pretty much an accident of the language that one needs a function to do this, which, unfortunately, opens the opportunity to give the "wrong name" to a function (in the sense that it can do something that the name doesn't imply, like concatenating strings).
In that sense, sum
is not a good name because it could also be called concatenate
.
A more neutral name, without semantic implications, would be to call it right_fold_plus
.
... or simply not give it a name it at all [](auto... xs) {return (xs + ...);}(1, 2, 3)
(see https://godbolt.org/z/7x9PzrzY1)