How to upcast an static std::optional

531 views Asked by At
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?

1

There are 1 answers

0
lubgr On BEST ANSWER

You cannot use std::optional for references. Instead, either use a raw pointer, a std::reference_wrapper, or boost::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 a Child instance. You can read more on that here.

Note that you can also use the nullptr-like state of std::unique_ptr and std::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, while std::optional is rather a good fit for value-type objects.