Search code examples
c++functionconstantsfunction-qualifier

Const function calling non const or vice versa (to avoid duplication)?


Is there any advantage using one over the other:

class Foo
{
public:
    const int& get() const
    {
        // stuff here
        return myInt;
    }

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

Or

class Foo
{
public:
    int& get()
    {
        // stuff here
        return myInt;
    }

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

I only used the first one, but I just saw the second one used somewhere, so I am wondering.

The comment // stuff here could be a non-trivial check like retrieving the index of a table in order to return a ref on a member of the table (for example: myInt = myTable[myComputedIndex];) so I cannot just make it public. Thus table and any member are not const.


Solution

  • If you have to make a function that is const-agnostic, and avoids duplication, one neat way to do it is delegating implementation to a template, for example

    class Foo {
    private: 
    
        int my_int;
        template <typename ThisPtr>
        static auto& get(ThisPtr this_ptr) { 
            return this_ptr->my_int;
        }
    
    public:
        int& get() {
            return get(this);
        }
    
        const int& get() const {
            return get(this);
        }
    };
    

    This way you are free from the fear associated with using const_cast, mutable and other stuff that goes into trying to reduce code duplication in cases like this. If you get something wrong, the compiler will let you know.