Boost logo

Boost Users :

Subject: [Boost-users] [program-options] Modifying the variable_value of a variables_map...
From: W Eryk Wolski (wewolski_at_[hidden])
Date: 2009-12-14 10:41:08


Hi,

I am using program options to parse cmdline parameters.
I would like to use the variable_map to pass parameters in my application
and I would like to modify the values of the
boost::program_options::variable_map.

while variable_value provides a method value() allowing me to modify the
content...
the variable_map "overrides" the operator[] of the std::map
const variable_value& operator[](const std::string& name) const;
so something like this (where mmap is a variable_map)
mmap["x"].value() = 2.;
does not compile.....

I tried this because the doc reads : The variables_map class can be used
just like std::map, except that values stored there must be retrieved with
the as method shown above. (If the type specified in the call to the
asmethod is different from the actually stored type, an exception is
thrown.)

Using the iterator it is
map_t::iterator it(mmap.find("x"));
boost::program_options::variable_value & vx(it->second);
vx.value() = 2.;
still easily possible to modify the variable_value .

I would like to better understand why the operator[] returns a const
variable_value?

regards
Eryk

Here is some sample code I wrote to test how to modify a variable_map.

boost::any a(1.);
boost::program_options::variable_value vv(a,false);
//variable_value provides the method value() returning a reference via which
I am able to modify the content.
// i.e.
vv.value() = 2.1;
//I store the variable_value in a variables_map
typedef boost::program_options::variables_map map_t;
map_t mmap;
mmap.insert( std::make_pair(std::string("x"), vv ) );
std::cout << mmap["x"].as<double>() << std::endl;
//now I would like to modify the value..
mmap["x"].value() = 2.; //does not compile.....
///error C2678: binary '=' : no operator found which takes a left-hand
operand of type 'const boost::any' (or there is no acceptable conversion)
// thats because abstract_variables_map defines the operator[] as follows
// const variable_value& operator[](const std::string& name) const;
//my workaround...
map_t::iterator it(mmap.find("x"));
boost::program_options::variable_value & vx(it->second);
vx.value() = 2.;
std::cout << mmap["x"].as<double>() << std::endl;

 --
Witold Eryk Wolski

Heidmark str 5
D-28329 Bremen
tel.: 04215261837



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net