const重载,而不必写入函数两次

const overloading without having to write function twice

本文关键字:两次 函数 重载 不必 const      更新时间:2023-10-16

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

假设我有一个带有memberfunction的c++类,该类重载了const,如下所示:

        Type*  DoSomething();
const   Type*  DoSomething() const;

如果这是一个更大、更复杂的成员,如何防止必须编写两次相同的代码?无法从const函数调用任何非const函数。从非const版本调用const版本会导致必须将const指针强制转换为非const(wich闻起来有点imo)。

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

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); }
};

在C++11中,您甚至可以去掉非推断模板参数,使用:

static auto DoSomethingImpl(T This) -> decltype(This->member)

您做过一次,如果要在类上使用const属性进行第二次操作,可以使用const_cast:

class Foo
{
          Type*  DoSomething()
  {
    // Lots of stuff
  }
  const   Type*  DoSomething() const
  {
    return const_cast<Foo*>(this)->DoSomething();
  }
}

使用模板方法模式从中提取公共代码。例如

inline const T* prev(size_t i) const
{
    return &FBuffer[ AdjustIndex(i) ];
}
inline T* prev(size_t i)
{
    return &FBuffer[ AdjustIndex(i) ];
}
inline size_t AdjustIndex( size_t i ) const
{
    return Math::ModInt( static_cast<int>( FHead ) - 1 - i, static_cast<int>( FBuffer.size() ) );
}

这种技术可以应用于许多情况(但不是所有情况,即如果行为显著不同)。