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();
}
4

1 回答 1

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;
    }
};
于 2021-04-26T10:37:36.010 回答