class Child: public Base {.....}
class Child
{
static std::optional<Base>& Child::GetBaseInstance()
{
static std::optional<Base> instance = std::make_optional<Chid>; \\Does not work. Please help
return instance;
}
}
I'm trying to return an instance but of type of std::optional of it's base. Also should I be returning std::optional& or std::optional<Base&> if I'm trying to pass the same reference?
You cannot use
std::optional
for references. Instead, either use a raw pointer, astd::reference_wrapper
, orboost::optional
(which works for references).That being said, you have another flaw in your snippet:
std::optional<Base>
suffers from object slicing when constructed from aChild
instance. You can read more on that here.Note that you can also use the
nullptr
-like state ofstd::unique_ptr
andstd::shared_ptr
to indicate the additional boolean property of your object. When dealing with class hierarchies, it often makes sense to use these smart pointers, whilestd::optional
is rather a good fit for value-type objects.