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)
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
.