开发者

macro solution for duplicate, const and non-const, getters?

开发者 https://www.devze.com 2023-03-27 09:54 出处:网络
Can this solution be turned into a macro so that I call something along the lines of: CALL_CONST_FUNC(objToReturn, thisPtr)->SomeConstFunc();

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 开发者_如何学Pythonerror prone.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消