Search code examples
c++c++11constantsconst-castboost-optional

Remove duplication in equivalent const and non-const members when returning optional reference by value


This answer explains how to remove duplication in equivalent const and non-const member functions which return by reference. It doesn't help, however, in the case where your function returns an optional reference to another type. Is there a solution for this case? E.g.,

class Foo {
    const boost::optional<const Bar&> get_bar() const;
    boost::optional<Bar&> get_bar();
}

Solution

  • You might do something similar to:

    class Foo {
        boost::optional<const Bar&> get_bar() const;
        boost::optional<Bar&> get_bar()
        {
            auto opt = static_cast<const Foo&>(*this).get_bar();
            if (opt) return const_cast<Bar&>(*opt);
            return boost::none;
        }
    };