T func(T A,T... B)
{
sum+=A;
func(B...);
}
This is not valid C++ syntax when func
is not a function template with T
its template parameter pack. ...
can only be used to expand packs; T
is a non-pack template parameter of the class template.
There are two ways to do this, depending on what you want to achieve.
One: If you want func
to accept a mix of arbitrary types, you can make it a (member) function template:
template <typename T>
class Myclass
{
public:
T sum;
template <class F1, class... F>
T func(F1 A, F... B)
{
sum+=A;
func(B...);
return sum;
}
template <class F>
T func(F A)
{
sum+=A;
return sum;
}
};
Two: If you want func
to only accept T
s, you can change it to use an initializer list:
template <typename T>
class Myclass
{
public:
T sum;
T func(std::initializer_list<T> A)
{
for (const auto& a : A)
sum+=a;
return sum;
}
};
Note that this will require calling it with a list in braces (e.g. func({1, 2, 42})
instead of func(1, 2, 42)
, but it's the approach also taken by e.g. std::max
.
Notice that there are a few issues in your code unrelated to the question at hand.
One, which I fixed in the example above, is that your first overload of func
didn't return anything. Calling it would result in Undefined Behaviour.
Another one, pointed out by @Zereges in the comments, is that T sum
is not initialised explicitly. If MyClass
is instantiated with a POD type (such as int
or double
), it will be used uninitialised. You should add a constructor for Myclass
:
Myclass() : sum{} {}