I expect the copy constructor approach to work, because, as said, it solves the type problem for the ternary operator. However, I do not know if the copy can be optimized.
However, in terms of readability, I would prefer:
boost::optional<A> buildA(state& st) { return st.flag1 ? A(st) : A(); } boost::optional<B> buildB(state& st) { return st.flag2 ? B(st) : B(); } C::C(state& st): _a(buildA(st)), _b(buildB(st)) {}
which is a bit more verbose. Copy optimization remains a good question.
Note: why are you using state& ? From this short example, a state const& would be better since the link was not taken from st .
Matthieu M.
source share