Opened 5 years ago

Closed 6 months ago

#7495 closed Feature Requests (fixed)

Support for boost::optional in boost::program_options

Reported by: Dmitry Trifonov <user61a@…> Owned by: vladimir_prus
Milestone: To Be Determined Component: program_options
Version: Boost 1.52.0 Severity: Optimization
Keywords: Cc:


It would be nice to allow support for boost::optional<T> arguments in program_options, so you can write following:

optional<std::string> optionalArg;
options_description   desc("allowed options");
desc.add_options() ("optional", value(&optionalArg), "specify optional argument");

And shouldn't bother with argument checking using variables_map.

Attachments (0)

Change History (8)

comment:1 Changed 3 years ago by anonymous

I am very interested in this as well!

comment:2 Changed 21 months ago by anonymous


comment:3 Changed 20 months ago by fakong@…

you only need to include this piece of code

template<class T> std::istream& operator>>(std::istream& in, boost::optional<T>& obj) {

T value; in >> value; obj = value; return in;


comment:4 Changed 20 months ago by vladimir_prus

It would seem such streaming support should be done in the optional library, not in program_options?

comment:5 Changed 20 months ago by Edward Catmur <ed@…>

Implementing optional support via streaming would have unwanted side effects. The correct place to implement optional support is via the validate customization point:

namespace boost {

template<class T>
void validate(boost::any& v, std::vector<std::string> const& values, boost::optional<T>* typeTag, int)
    if (!values.empty())
        boost::any a;
        using namespace boost::program_options;
        validate(a, values, (T*)0, 0);
        v = boost::any(boost::optional<T>(boost::any_cast<T>(a)));


comment:6 Changed 20 months ago by vladimir_prus

Pull request will be welcome. Is there a way to implement this with a forward declaration, so that program_options do not have to depend on boost::optional.

comment:7 Changed 20 months ago by Edward Catmur <ed@…>

Submitted pull request:

Uses forward declaration to avoid dependency (except in tests).

comment:8 Changed 6 months ago by vladimir_prus

  • Resolution set to fixed
  • Status changed from new to closed

Add Comment

Modify Ticket

Change Properties
Set your email in Preferences
as closed The owner will remain vladimir_prus.
The resolution will be deleted. Next status will be 'reopened'.

E-mail address and user name can be saved in the Preferences.

Note: See TracTickets for help on using tickets.