Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use boost::optional to pass optional input parmemters

Tags:

c++

boost

How do I use a API that takes a list of boost::optional parameters? I have not found any documentation that talks about input parameters,

This and this does not talk about how to handle input parameters. Please let me know what I am missing.

here it is

void myMethod(const boost::optional< std::string >& name,
const boost::optional< std::string >& address,
const boost::optional< boost::string >& description,
const boost::optional< bool >& isCurrent,
const boost::optional< std::string >& ProductName,
const boost::optional< std::string >& Vendor)

Given that, how should I call it? myMethod(,,,,x,y) did not work

like image 525
learningtocode Avatar asked Mar 10 '15 02:03

learningtocode


1 Answers

For a function such as:

void myMethod( boost::optional<int>, boost::optional<double> );

You can pass boost::none as any of the boost::optional parameters to specify "none":

myMethod( boost::none, 1.0 );

In C++11 or later, an explicit default-constructed object is even less typing.

myMethod( {}, 1.0 );

If you want to completely omit any mention of the parameter, C++ requires default parameters only after specified parameters.

void myMethod( boost::optional<int> = boost::none_t,
               boost::optional<double> = boost::none_t );

myMethod( 42 ); // (The second parameter will be boost::none_t

You would need to overload your function with different parameter orderings to allow any parameter to be omitted.

void myMethod( boost::optional<int> = boost::none,
               boost::optional<double> = boost::none );

// Alternate parameter ordering
void myMethod( boost::optional<double> d,
               boost::optional<int> i = boost::none )
{
    myMethod( i, d );
}

myMethod( 1.0 ); // (The "int" parameter will be boost::none
like image 70
Drew Dormann Avatar answered Sep 27 '22 22:09

Drew Dormann