c++boostboost-program-options

Insert into boost::program_options::variables_map by index operator


I have a boost::program_options::variables_map args. Now I want to insert into this map manually like a key-value pair. Example:

boost::program_options::variables_map args

args["document"] = "A";

args["flag"] = true;

The problem is that I already have these 2 options

desc.add_options()
    ("document", po::value<std::string>())
    ("flag", po::value<bool>());

but they are given empty input from the command line sometimes. So if they are empty, then I have to update them inside the po::variables_map args itself


Solution

  • Since it publicly inherits from std::map<std::string, variable_value> it should be relatively safe to cast it to std::map and use as such:

    (*static_cast<std::map<std::string, variable_value>*>(my_variable_map))[name] = value;
    

    There's no guarantee that this is enough to make variable_map use it, but currently it seems to be: cpp, h.

    It's annoying that this is needed.