Constructor similar to std::map or std::vector in a class

c++, c++11, std, vector

Solution

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

Problem

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`.

Original source

Related problems