const重载,而不必写入函数两次
const overloading without having to write function twice
可能重复:
重复、常量和非常量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() ) );
}
这种技术可以应用于许多情况(但不是所有情况,即如果行为显著不同)。
相关文章:
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- C++析构函数调用两次,堆栈分配的复合对象
- C++两次定义相同的函数会导致错误
- 对于优化级别为 0 的 std::vector,析构函数被调用两次
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取
- 为什么这个自定义分配器的析构函数在 GCC/MSVS 的 stdlib 中被调用两次
- 调用某个回调函数两次会导致分段错误:Nan
- C++:链接库两次,全局构造函数运行两次吗?
- 执行函数两次
- 重载运算符 new(),为什么构造函数被调用两次?
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 为同一存储位置调用构造函数两次是否合法?
- 为什么在下面的代码中调用复制构造函数两次
- 两个单链列表共享同一个节点和析构函数两次删除相同的内存
- 析构函数在 lambda 捕获说明符中声明的类实例上运行两次
- 为什么在这里调用析构函数两次
- while 循环在一个函数调用中执行两次
- 为什么这个构造函数被调用两次
- 用define替换两次函数调用