12

I'm creating a class and I want to know how to create a constructor similar to the std::map or std::vector style.

std::map<std::string, std::string> map = {
    {"foo", "bar"},
    {"biz", "buz"},
    {"bez", "boz"}
};

The difference is that I don't want my class to ask for types that wants to accept, just like std::map does.

std::map<std::string, std::string>

I want my class to accept that style of arguments:

{
    {"foo", "bar"},
    {"biz", "buz"},
    {"bez", "boz"}
};

But with defined type. (std::string, Typer)

The 'Typer' is a class that I will insert as value on the std::map.

David Starkey
  • 1,840
  • 3
  • 32
  • 48
SH.0x90
  • 532
  • 2
  • 7
  • 19
  • You can't deduce initializer lists. – Kerrek SB Feb 21 '14 at 15:36
  • 1
    The simple answer is: use the map as the second parameter, as follows: const std::map& data. In this case you can use your syntax for the second parameter. This is not a duplicate question, by the way. You needn't use an initializer list here. This works both in VS2013 and GCC 4.8.1. – Mikhail Semenov Mar 02 '14 at 10:54

2 Answers2

24

If I understand your question correctly, you want a constructor taking std::initializer_list<std::pair<std::string, Typer>>, like this:

struct Typer
{
  std::string data;

  Typer(const char *s) : data(s) {}
};


struct MyClass
{
  MyClass(std::initializer_list<std::pair<std::string, Typer>> i)
    : myMap(begin(i), end(i))
  {}

  std::map<std::string, Typer> myMap;
};

int main()
{
  MyClass m = {
    {"foo", "bar"},
    {"biz", "buz"},
    {"bez", "boz"}
  };
}

Live example

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
3

typedef std::map<std::string, Typer> MyType;

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055