Reputation: 13
i try to understand the use of recursive constructors with variadic templates.
In the following code i want to implement a recursive constructor with variadic passed values.
template <class T, class... T2>
struct Tuple{
T value;
Tuple(T n){ //constructor if only one value left
value = n;
}
Tuple(T n, T2... re){ //constructor if more than one value left
T value = n;
//Tuple(rest...); doesnt work for me
}
};
int main(){
Tuple<int, float, int> t(2, 1.2, 9);
std::cout << t.value << "\n"; //2
std::cout << t.rest.value << "\n"; //1.2
std::cout << t.rest.rest.value << "\n"; //9
}
Upvotes: 1
Views: 368
Reputation: 66230
You have also to inherit from Tuple<T2...>
template <class T, class... T2>
struct Tuple : public Tuple<T2...>
and initialize the inherited class in the initialization list (before value
) [caution code not tested]
Tuple(T n, T2... re) : Tuple<T2...>{re...}, value{n}
{ }
You also need a ground case specialization to stop the recursion
Something as
template <class T>
struct Tuple<T>
{
T value;
Tuple (T n) : value{n}
{ }
};
or also (maybe simpler)
template <>
struct Tuple<>
{ };
But for this second solution, you have to define Tuple
as receiving zero or more types; maybe something as follows
template <typename...>
struct Tuple
{ };
template <class T, class... T2>
struct Tuple<T, T2...> : public Tuple<T2...>
{
// ...
};
This way, when Tuple
receive at least one type, the specialization is selected; when receive zero type, only the main version match and serve as ground case.
Upvotes: 3