Modify

Opened 5 years ago

Closed 11 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:

Description

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 2 years ago by anonymous

+1

comment:3 Changed 2 years 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 2 years ago by Vladimir Prus

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

comment:5 Changed 2 years 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 2 years 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 2 years ago by Edward Catmur <ed@…>

Submitted pull request: https://github.com/boostorg/program_options/pull/18

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

comment:8 Changed 11 months ago by Vladimir Prus

Resolution: fixed
Status: newclosed

Modify Ticket

Change Properties
Set your email in Preferences
Action
as closed The owner will remain Vladimir Prus.
The resolution will be deleted.

Add Comment


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

 
Note: See TracTickets for help on using tickets.