Elegant solution to duplicate, const and non-const, getters?

c++, constants, function-qualifier

Solution

I recall from one of the Effective C++ books that the way to do it is to implement the non-const version by casting away the const from the other function.

It's not particularly pretty, but it is safe. Since the member function calling it is non-const, the object itself is non-const, and casting away the const is allowed.

class Foo
{
public:
    const int& get() const
    {
        //non-trivial work
        return foo;
    }

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

Problem

Don't you hate it when you have ``` class Foobar { public: Something& getSomething(int index) { // big, non-trivial chunk of code... return something; } const Something& getSomething(int index) const { // big, non-trivial chunk of code... return something; } } ``` We can't implement either of this methods with the other one, because you can't call the non-`const` version from the `const` version (compiler error). A cast will be required to call the `const` version from the non-`const` one. Is there a real elegant solution to this, if not, what is the closest to one?

Original source

Related problems