Opened 10 years ago

Closed 6 years 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.

Change History (8)

comment:1 by anonymous, 8 years ago

I am very interested in this as well!

comment:2 by anonymous, 7 years ago

+1

comment:3 by fakong@…, 7 years ago

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 by Vladimir Prus, 7 years ago

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

comment:5 by Edward Catmur <ed@…>, 7 years ago

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 by Vladimir Prus, 7 years ago

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 by Edward Catmur <ed@…>, 7 years ago

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

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

comment:8 by Vladimir Prus, 6 years ago

Resolution: fixed
Status: newclosed
Note: See TracTickets for help on using tickets.