简体   繁体   English

类似于std :: map或std :: vector的构造函数

[英]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::mapstd::vector样式的构造函数。

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::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) (std :: string,Typer)

The 'Typer' is a class that I will insert as value on the std::map . 'Typer'是一个我将在std::map上作为值插入的类。

If I understand your question correctly, you want a constructor taking std::initializer_list<std::pair<std::string, Typer>> , like this: 如果我正确理解你的问题,你想要一个构造函数采用std::initializer_list<std::pair<std::string, Typer>> ,如下所示:

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 实例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM