2

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
  • 13
  • 116
  • 190
Irbis
  • 1,432
  • 1
  • 13
  • 39

1 Answers1

5

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055