0

The line attempting to add_options() of type std::optional<string> results in a compile error. does boost::program_options not support this type? how are optional options managed w/ boost::program_options?

#include <iostream>
#include <optional>
using namespace std;
#include <boost\program_options.hpp>
using namespace boost;

int main(int argc, const char* argv[])
{
     cout << "Hello World\n" << boolalpha;

     program_options::options_description options_description("options");
     options_description.add_options()
          ("help", "please help me get this code to compile w/o error . the line below needs to be commented out for a clean compile . does boost not permit an options optional<> type ? Thank You Kindly")
          ("optional string", program_options::value<std::optional<string>>, "this option is optional")
          ;
}

expected clean compile and boost::program_options to support std::optional<> type

James Z
  • 12,209
  • 10
  • 24
  • 44
  • 1
    ***the line attempting to add_options() of type std::optional results in a compile error*** What error? Please add the exact text of the error message as text. No pictures of text. – drescherjm Feb 17 '23 at 19:18
  • 1
    After fixing the include to use / instead of \ I was able to get the errors: [https://godbolt.org/z/d85jE5nv8](https://godbolt.org/z/d85jE5nv8) – drescherjm Feb 17 '23 at 19:22
  • @drescherjm those are likely not the errors you (or OP) were looking for. The code was cute, but sloppy copy-paste practice (not to mention `using namespace *;` abuse :)) – sehe Feb 17 '23 at 21:55

1 Answers1

1

You forgot to call value<>().

Besides, optional options are represented by either

  • no value stored inside the variable_map
  • or the default value (from the option_description) stored inside the variable_map

I explained the background in a similar situation here: Using Boost::optional with ->multitoken and/or ->composing()

Of course, you can insist in your case, e.g. because you want to supply boost::none as the default value (just making things up for the story-line, albeit far-fetched). In that case, I suggest boost::optional as it enjoys library support:

Live On Coliru

#include <iostream>
#include <boost/optional.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;

int main(/*int argc, char const* argv[]*/) {
    std::cout << std::boolalpha;

    po::options_description options_description("options");
    options_description.add_options()                                                             //
        ("optional string", po::value<boost::optional<std::string>>(), "this option is optional") //
        ;
}

If you must have std::optional<> support you'll have to add it yourself: Using boost::program_options with std::optional

sehe
  • 374,641
  • 47
  • 450
  • 633