1

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();
}
  • Are you returning a reference to a member variable of type `Bar`? Please edit the question to include a [mre], in particular why the linked solution doesn't work. – cigien Apr 25 '21 at 21:16
  • You might need to unpack the optional and pack a new one as shown here: https://stackoverflow.com/a/28347423/21974 As it gets rather intricate, maybe the better design is to have two different methods that use several helper methods for avoiding the code duplication. Also what is the use of a optional reference type? Why not simply a pointer then (which is either valid or `nullptr`)? – ypnos Apr 25 '21 at 21:18

1 Answers1

0

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;
    }
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302