Dav*_*var 4 c++ methods return constants const-cast
const_cast 可以用于创建已实现方法的非常量版本吗?我想我看到了一些类似的内容(建议使用 const 方法来完成实际工作),但我不太确定它应该如何工作。
Value& const search(key) const {
// find value with key
return value;
}
Value& search(key) {
return const_cast<Value&>(search(key));
}
Run Code Online (Sandbox Code Playgroud)
如果不是这样,那么在没有代码重复的情况下创建非常量函数的推荐方法是什么?
最简单的方法是使用as_constC++17:
Value& search(key) {
return const_cast<Value&>(std::as_const(*this).search(key));
}
Run Code Online (Sandbox Code Playgroud)
没有它你可以这样做(或者自己实现,这不是很难)
Value& search(key) {
return const_cast<Value&>(static_cast<const T&>(*this).search(key));
}
Run Code Online (Sandbox Code Playgroud)
T你的类的类型在哪里(你可以有一个通用的解决方案decltype,但由于decltype(*this)是引用类型,它变得非常丑陋)。
| 归档时间: |
|
| 查看次数: |
358 次 |
| 最近记录: |