How to implement a member function once for both non-const and const overloads?

Viewed 59

Sometimes I find myself adding overloads that have the same implementation, with const in qualifier and return value being the only difference:

struct B {};
struct A {
    const B& get(int key) const
    {
        if (auto i = map.find(key); i != map.end())
            return i->second;
        throw std::runtime_error{""};
    }

    B& get(int key)
    {
        if (auto i = map.find(key); i != map.end())
            return i->second;
        throw std::runtime_error{""};
    }

private:
    std::unordered_map<int, B> map;
};

Is there an idiomatic way to write the implementation only once and get rid of copy-paste that is better than const_cast:

const B& get(int key) const
{
    return const_cast<A*>(this)->get(key);
}

?

1 Answers

Scott Meyers' advice:

When const and non-const member functions have essentially identical implementations, code duplication can be avoided by having the non-const version call the const version.

Related