mardi 29 mars 2022

Forward initializer list to map attribute(s)

I would like to use initializer lists to initialize some attributes, here is the code:

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


using namespace std;

typedef struct A {
  A(initializer_list<pair<string,string>> l1,
    initializer_list<pair<string,string>> l2) : att1(l1), att2(l2)
  {
  }
  map<string, string> att1;
  map<string, string> att2;
} A;

int main (int argc, char *argv[])
{
  A a{
    ,
    ,
  };
  for (auto &[key, value]: a.att1)
    cout << key << ": " << value;
  cout << endl;

  for (auto &[key, value]: a.att2)
    cout << key << ": " << value;
  cout << endl;
  return 0;
}

The compilation fails:

initializer.cpp:11:49: error: no matching constructor for initialization of 'map<std::string, std::string>' (aka 'map<basic_string<char, char_traits<char>, allocator<char>>, basic_string<char, char_traits<char>, allocator<char>>>')
    initializer_list<pair<string,string>> l2) : att1(l1), att2(l2)

How can I forward an initializer list (multiple if possible) from the constructor to initialize some attributes?

Edit: I know that since this is a struct it provide an initializer_listconstructor for its members, but this is a toy example and in the real case I use a class with private members.

Aucun commentaire:

Enregistrer un commentaire