1

I'm familiarizing myself with boost::program_options (and C++ in general). I wrote the function below, but I can't quite understand the error I'm getting. Here's the code (note that po is an alias for boost::program_options).

int application(po::variables_map& vm)
{
    std::cout << &vm << std::endl;
    std::cout << vm["infile"];

    return SUCCESS;
}

The error I'm receiving is for the second line in the function body. It reads: "no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘const boost::program_options::variable_value’)"

What am I doing wrong?

Louis Thibault
  • 20,240
  • 25
  • 83
  • 152
  • The error message is actually pretty straightforward for once: there’s no overload for `<<` which works with `program_options::variable_value`. – Konrad Rudolph May 18 '13 at 18:38
  • @KonradRudolph, right... how would I cout the contents of the variable_value type, then? Surely there must be a way to access the std::string I put in there. – Louis Thibault May 18 '13 at 18:40
  • 1
    I don’t think there is – nor that there should be. `variable_value` is an opaque type that can hold any kind of value, and the only operation it supports is retrieving that value and storing it somewhere else, with the correct type. That’s it. *If you know the type* then you can retrieve it via `as`: `std::cout << vm["infile"].as();`. – Konrad Rudolph May 18 '13 at 18:47
  • @KonradRudolph, Thanks, that's exactly what I was looking for. Apologies if I was unclear! – Louis Thibault May 18 '13 at 18:54

1 Answers1

0
std::cout << vm["infile"].as<std::string>() << std::endl;

This only works if you know the underlying type. It uses boost::any and boost::any_cast in the implementation. If the value is not a string in the above example, it will throw a boost::bad_any_cast exception.

If there are only few possible types, you can chain try/catch or use typeid to discover what the correct type is. That would be super hacky of course. :)

ejgottl
  • 2,809
  • 19
  • 18