0

Someone recently demonstrated a C++ horribleness (here):

cout << string(50, 'x'); // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
cout << string{50, 'x'}; // 2x

std::string sees the second line as an initialiser list.

I'm very fond of using {} initialiser syntax, however I'm about to implement a class that could be initialised with an initialiser list.

Is there any way to code the following syntax:

Foo{x};        // initialise a Foo object with x
Foo{{x,y,z}};  // initialise a Foo object with initialiser list
Foo{{x}};      // initialise a Foo object with initialiser list with ONE item
Community
  • 1
  • 1
P i
  • 29,020
  • 36
  • 159
  • 267
  • @remyabel, string{50, 'x'} -- are we initialising with a char and a repeat-count, or with a list of chars? The compiler resolves the ambiguity by preferring the latter, but I would like to resolve it syntactically, to make my code read better. – P i Dec 11 '14 at 09:48
  • @Pi: List of chars, of course. One of the motivating factors for having two forms is because you want to allow two behaviors (in particular, the two behaviors you showed in your example). – MSalters Dec 11 '14 at 10:10
  • `string{50,'x'}` uses *initializer-list* and the documentation says that it construct the string with the content of the list, so a list of chars... – Jean-Baptiste Yunès Dec 11 '14 at 10:12
  • Have you tried overloading the constructor on X and std::initializer_list{x} ? Do you want to do anything different when given one object, as opposed to when given a list of one? – Bulletmagnet Dec 11 '14 at 12:22
  • If you have an initializer-list constructor, `Foo{x};` is going to go to that unless it is completely nonviable. – T.C. Dec 11 '14 at 12:33

1 Answers1

0

In the end I solved this problem by having my class use a variadic parameter pack rather than an initializer list.

I haven't yet come across an example where you can't bypass initializer lists in this way.

P i
  • 29,020
  • 36
  • 159
  • 267