Possible Duplicate:
Elegant solution to duplicate, const and non-const, getters?
假设我有一个带有成员函数的 C++ 类,它为 const 重载,如下所示:
Type* DoSomething();
const Type* DoSomething() const;
如果这是一个更大、更复杂的成员,如何避免必须两次编写相同的代码?不能从常量函数调用任何非常量函数。从非 const 调用 const 版本会导致 const 指针必须转换为非 const(imo 有点味道)。
您可以委托(delegate)给模板静态成员函数,如:
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)