const重载而不必写两次函数

Uni*_*ant 7 c++ overloading const

可能重复:
重复,常量和非常量,getter的优雅解决方案?

假设我有一个c ++类,其成员函数为const重载,如下所示:

        Type*  DoSomething();
const   Type*  DoSomething() const;
Run Code Online (Sandbox Code Playgroud)

如果这是一个更大,更复杂的成员,那么如何防止必须两次编写相同的代码?不能从const中调用任何非const函数.从非const中调用const版本会导致一个const指针必须被转换为非const(这有点像imo).

Ben*_*igt 7

您可以委托模板静态成员函数,如下所示:

class Widget
{
    Type member;

    template<typename Result, typename T>
    static Result DoSomethingImpl(T This)
    {
        // all the complexity sits here, calculating offsets into an array, etc
        return &This->member;
    }

public:
            Type*  DoSomething() { return DoSomethingImpl<Type*>(this); }
    const   Type*  DoSomething() const { return DoSomethingImpl<const Type*>(this); }
};
Run Code Online (Sandbox Code Playgroud)

在C++ 11中,您甚至可以删除非推断模板参数,其中:

static auto DoSomethingImpl(T This) -> decltype(This->member)
Run Code Online (Sandbox Code Playgroud)