1

I was playing around with variadic templates and decided to implement my own tuple class. But when I tried to implement the constructors, I discovered that the implicitly created constructors seem to cover what i was about to build. Consider to following code.

template<typename ... Tail> struct mytuple { };

template<typename Head, typename ... Tail>
struct mytuple<Head, Tail...>
{
    Head head;
    mytuple<Tail...> tail;
};

int main()
{
    mytuple<int, int, int> t1{1,2,3};        // <--
    mytuple<int, int, int> t2{1,{2,{3,{}}}};
}
  • Why does the the simple brace-initialization t1{1,2,3} already work?
  • Which constructor is called here?
  • Why does the second initialization t2{1,{2,{3,{}}}} work as well and not only one and not the other?

My guess is that this "magic" is done by some implicitly defined initializer-list constructor (since C++11 I'm not sure which constructors are defined under which conditions). In case of the second tuple t2{1,{2,{3,{}}}} I kind of understand why this is working, since the structure of the braces is reflecting the structure of the constructed class. But to my surprise both variants seem to work.

mic
  • 821
  • 6
  • 18
  • I've explained this in the duplicate. C++14 has relaxed some rules though, discussed in the duplicate; see this : [`slight relaxation of the rules for eliding braces`](http://stackoverflow.com/questions/18792731/can-we-omit-the-double-braces-for-stdarray-in-c14) – Nawaz Oct 16 '14 at 09:25
  • @Nawaz: You can argue that this is a duplicate, but I think this is not that obvious. I had to read into a lot of other resources to understand why your answer also applies to my question. But I think your quote of the C++11 spec explains it. – mic Oct 16 '14 at 20:24
  • If you don't know the stuffs, then obviously it is **not** obvious to you. However, once you know the explanation, it becomes obvious. – Nawaz Oct 17 '14 at 02:12

0 Answers0