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.
operator+
could do lots of things. Matrices have a+
and so do strings - what happens when you add a matrix to a string? Or are you saying that all the types passed to this function can be added to each other (like sometimes multiple matrices will be passed and sometimes multiple strings will be passed)? – ThujaFoo
and classBar
and overloaded the '+' operator to add instances of both, the function should allow you to. If you were to try to add something like a string and an int, for which an overload of the operator+ does not exist, that would just throw a compilation error, which is fine. – Biographer+
doesn't always meansum
, and you are not conveying that in any way. The language can't help much with that unfortunately, there are several ways to improve the quality of the code, 1) use a named concept in the class template<class... Arithmetic> auto sum( etc
2) do not imply semantic meaning in the function<class... Arithmetic> auto fold_plus( etc
3) do not name anything (use lambda) (see my answer). – Nigro+
to represent asum
. I just named the function that as an example, but ultimately I should have just named itplus
. It is not meant to be thesum
or anything. It is just supposed to implement the+
operator upon the parameters. – Biographerright_fold
, but I should have asked which one you wanted to do. Of course, it is a bad idea to use+
for noncommutative operations (likestd::string
does), but that is another story. – Nigrodecltype
doesn't solve the conceptual semantic problem. It only adds SFINAE to your function, which you might or might not want. – Nigro