Modify

Ticket #7495 (closed Feature Requests: fixed)

Opened 5 years ago

Last modified 4 months ago

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

Change History

comment:1 Changed 3 years ago by anonymous

I am very interested in this as well!

comment:2 Changed 19 months ago by anonymous

+1

comment:3 Changed 19 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 19 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 18 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 18 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 18 months 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 4 months ago by vladimir_prus

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

Add a comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
The resolution will be deleted. Next status will be 'reopened'
Author


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

 
Note: See TracTickets for help on using tickets.