1

Can this solution be turned into a macro so that I call something along the lines of:

CALL_CONST_FUNC(objToReturn, thisPtr)->SomeConstFunc();

For functions that return a value and another for functions that don't. My macro token skills are not that great so I thought maybe someone here can come up with one (or tell me that it is not possible). Ultimately the goal is to avoid writing the ugly one-liner and replace it with something that is easy on the eyes and not error prone.

Community
  • 1
  • 1
Samaursa
  • 16,527
  • 21
  • 89
  • 160

1 Answers1

0

If a function doesn't return a value (reference or pointer), do you need const overloads in the first place? It seems that the only reason to have two is to get a const or non-const reference out of the class. Otherwise the const version alone should be enough.

As to making the idiom sweeter, how about a few template helpers instead to do type deduction for you:

template <class T>
const T& add_const(T& t) { return t; }

template <class T>
T& remove_const(const T& t) { return const_cast<T&>(t); }

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

    int& get()
    {
        return remove_const(add_const(*this).get());
    }
};

The benefit is greater if the type names are longer.

UncleBens
  • 40,819
  • 6
  • 57
  • 90
  • `If a function doesn't return a value (reference or pointer), do you need const overloads in the first place?` Good point! ... and I like this solution (+1) – Samaursa Aug 11 '11 at 13:26
  • If your const version of the function returns something that is supposed to be write protected, your will accidentally make whatever is returned write accessible by pulling this trick. – HelloGoodbye Mar 28 '13 at 07:12