The following code compiles and runs on MSVC 2019 and Clang trunk. (I think it needs at least C++17). It does not run on gcc-trunk and I believe the consensus is that this is due to a bug in gcc.
However, when any of the elements are replaced by a user type or a pointer type, it fails on all compilers. To see this, uncomment the tuple_c definition near the end.
I'm actually slightly surprised this works at all since it appears to be specializing a function with a universal-ref parameter with one that has an r-value-ref parameter. Maybe that's ok? If it is, why is it failing with the struct?
Is there a better way of writing this? I mean in general. I'm well aware of std::tuple.
#include <iostream>
using namespace std;
template <typename... TP> class Tuple
{
};
template <> class Tuple <>
{
};
template <typename Head, typename... Tail> class Tuple <Head, Tail...>
{
Head head;
Tuple <Tail...> tail;
public:
Tuple ()
{
}
Tuple (const Head& head_in, const Tail&...tail_in)
: head (head_in), tail (tail_in...)
{
}
template <int i> auto Get ()
{
return tail.template Get <i-1> ();
}
template <> auto Get <0> ()
{
return head;
}
template <int i, typename T> void Set (T&& v) // T&& is a universal ref
{
tail.template Set <i-1, T> (static_cast <T&&> (v));
}
template <int i, typename T> void Set (const T& v)
{
tail.template Set <i-1, T> (v);
}
template <> void Set <0, Head> (Head&& v) // Head&& is an rv-ref
{
head = v;
}
template <> void Set <0, Head> (const Head& v)
{
head = v;
}
};
template <typename Head, typename... Tail> Tuple <Head, Tail...> MakeTuple (Head&& head, Tail&&...tail)
{
Tuple <Head, Tail...> result (head, tail...);
return result;
}
struct S
{
int x;
int y;
};
ostream& operator << (ostream& out, const S& s)
{
out << "{" << s.x << "," << s.y << "}";
return out;
}
int main(int argc, char* argv[])
{
auto tuple_a = MakeTuple (1,2,3,4);
tuple_a.Set <1,int> (42);
cout << tuple_a.Get <0> () << '\n';
cout << tuple_a.Get <1> () << '\n';
cout << tuple_a.Get <2> () << '\n';
cout << tuple_a.Get <3> () << '\n';
auto tuple_b = MakeTuple (1,2.3f,3,4);
tuple_b.Set <1,float> (42.3f);
cout << tuple_b.Get <0> () << '\n';
cout << tuple_b.Get <1> () << '\n';
cout << tuple_b.Get <2> () << '\n';
cout << tuple_b.Get <3> () << '\n';
S s {4,5};
//auto tuple_c = MakeTuple (1,2.3f,3,s);
return 0;
}