Kamal Raydan
Kamal Raydan

Reputation: 45

What is the simplest way of filling in a map within a map that contains `std::variant` in C++?

So I want to have a variable that is of type map < string, map<string, variant<bool, vector<int>>> > args.

How can one go about filling this in, not just on the first level (i.e. the first map) but the second level (i.e. the second map) which in fact is of type std::variant which doesn't support the typical args['level1']['level2']?

I have tried using a for loop, looping over a vector of strings, but i'm not sure this is going anywhere:

    for (unsigned i=0; i<objects.size(); i++) {
        
        // Create the obj_dict
        obj_dict.insert({objects.at(i), })
        obj_dict.insert({"Missing", false})
        obj_dict.insert({"Obstructed", false})
        obj_dict.insert({"Moved", false})
        obj_dict.insert({"Gone", false})
    }

P.S This is what it would ideally look like,

    map < string, map<string, variant<bool, vector<int>>> > args{
        {"Head", {
            {"coords", {1,2,3}},
            {"missing", false},
            {"obstructed", false},
            {"moved", false},
            {"gone", false},
        }},
        {"Arm", {
            {"coords", {1,2,3}},
            {"missing", false},
            {"obstructed", false},
            {"moved", false},
            {"gone", false}
        }}
    };

Upvotes: 1

Views: 70

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

The problem here is that braced initialization lists will not survive a trip through a forwarding reference that's used to construct a variant.

You'll have to be a little bit more explicit:

#include <variant>
#include <map>
#include <string>
#include <vector>

std::map <std::string, std::map<std::string,
                std::variant<bool,
                         std::vector<int>>> > args{
        {"Head", {
            {"coords", std::vector<int>{1,2,3}},
            {"missing", false},
            {"obstructed", false},
            {"moved", false},
            {"gone", false},
        }},
        {"Arm", {
            {"coords", std::vector<int>{1,2,3}},
            {"missing", false},
            {"obstructed", false},
            {"moved", false},
            {"gone", false}
        }}
    };

Upvotes: 1

Related Questions