std::optional<Class> a;
a.value_or( Class() ).GetMember();
Why cant we do this like:
a.value_or().GetMember();
Can standard specialize value_or
on a default constructible basis?
1 Answer
Unfortunately this value_or
doesn’t have this option and I agree with with Max Langhof’s comment that it should be a separate function value_or_default
.
Nevertheless I’ve put together a little workaround for your case:
struct default_constructor_t {
explicit default_constructor_t() = default;
};
inline constexpr default_constructor_t default_constructor{};
class Class {
...
Class(default_constructor_t) : Class{} {}
...
};
int GetMember(std::optional<Class> Object) {
return Object.value_or(default_constructor).GetMember();
}
In this solution, you need to add an additional implicit constructor to your class. This solution is also lazy. It will call default constructor only if optional
doesn’t have a value.
Archive from: https://stackoverflow.com/questions/59035592/why-stdoptionalvalue-or-dont-have-a-specialization-for-default-ctor-types