Quick Q: How can I make my constructor take a list of things, like map and vector? -- StackOverflow

Quick A: By having your constructor take an initializer_list<> of the appropriate type.

Today on StackOverflow:

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

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.

Thank you.

Add a Comment

Comments are closed.

Comments (1)

0 0

Mikhail Semenov said on Mar 2, 2014 04:06 AM:


#include <iostream>
#include <string>
#include <map>

typedef std::map<std::string, std::string> MyDataType;

class MyClass
{
std::string name;
MyDataType data;

public:
MyClass(const std::string& name1, const MyDataType& data1) :name(name1), data(data1){}

MyDataType getData() { return data; }
std::string getName() { return name; }

};


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

MyDataType data = x.getData();
for (auto& elem : data)
{
std::cout << elem.first << " " << elem.second << std::endl;
}

return 0;
}


This code works both in VS2013 and GCC 4.8.1