vendredi 25 juin 2021

How std::initializer_list works with multiple curlys {}?

I have a following code:

Let's start with 2 curlys since it obvious from the declaration.

#include <iostream>

template <typename T>
struct Box {
  Box(std::initializer_list<T>) {}
};

template <typename T>
struct Pen {
   Pen(T) { puts("only int"); }
};

int main() {
  Box< Box<Pen<int>> > vi  { { 3, 3, 2 } } ;         // works  
  Box< Box<Pen<int>> > vi2 { { {3, 3, 2} } } ;       // works
  Box< Box<Pen<int>> > vi3 { { { { 3, 3, 2 } } } } ; // works
  Box< Box<Pen<int>> > vi4 { { { { {3, 3, 2} } } } }; // error
}

If I throw initializer_list constructor in the mix then,

template <typename T>
struct Pen {
   Pen(T) { puts("only int"); }
   Pen(std::initializer_list<T>) { puts("init list"); }
};

int main() {
  Box< Box<Pen<int>> > vi  { { 3, 3, 2 } } ;
  Box< Box<Pen<int>> > vi2 { { {3, 3, 2} } } ;
  Box< Box<Pen<int>> > vi3 { { { { 3, 3, 2 } } } } ;
  Box< Box<Pen<int>> > vi4 { { { { {3, 3, 2} } } } } ;
  Box< Box<Pen<int>> > vi5 { { { { { {3, 3, 2 } } } } } } ;
  Box< Box<Pen<int>> > vi46 { { { { { { {3, 3, 2 } } } } } } } ;
}

Except the last one, everything works. How to understand curlys and initializer_list constructors?

Aucun commentaire:

Enregistrer un commentaire