How to forward constructor arguments to boost::optional

853 Views Asked by At

I have the following simple struct:

struct X
{
    X(std::string name, int value): name_(name), value_(value){}

    std::string name_;
    int value_;
};

I would like to use it with boost optional without copying. Here is one option:

boost::optional<X> op;
op.emplace("abc", 5);

Is it possible without using emplace function ? (I mean one line expression)

1

There are 1 best solutions below

4
Lightness Races in Orbit On BEST ANSWER

Yeah, just construct it with the "in place" tag which forwards ctor args!

boost::optional<X> op(boost::optional::in_place_init, "abc", 5);

(ref)

FWIW if you don't mind a move then this works too:

boost::optional<X> op(X("abc", 5));

Scan down that reference page; there are loads of ways to construct or fill a boost::optional.