使用 const_cast 创建方法的非常量变体
Using const_cast for creating non-const variant of methods
const_cast 能否用于创建已实现方法的非常量版本?我想我看到了一些类似的东西(建议使用 const 方法来完成实际工作),但我不太确定它应该如何工作。
Value& const search(key) const {
// find value with key
return value;
}
Value& search(key) {
return const_cast<Value&>(search(key));
}
如果不是这样,创建没有代码重复的非常量函数的推荐方法是什么?
最简单的方法是使用 C++17 中的 as_const
:
Value& search(key) {
return const_cast<Value&>(std::as_const(*this).search(key));
}
没有它你也可以这样做(或者自己实现,不是很难)
Value& search(key) {
return const_cast<Value&>(static_cast<const T&>(*this).search(key));
}
其中 T
是您的 class 的类型(您可以使用 decltype
的通用解决方案,但由于 decltype(*this)
是引用类型,它变得非常难看).
您可以查看 as_const
实现 here or the generic cast here。
两种方法。
第一个:
namespace notstd{ // backported C++17
template<class T>
T const& as_const(T& t){return t;}
template<class T>
T const&& as_const(T&& t){return t;}
}
namespace utility { // not ever in std
template<class T>
T& remove_const(T const& t){return const_cast<T&>(t);}
template<class T>
T&& remove_const(T const&& t){return const_cast<T&&>(t);}
}
然后:
Value& const search(Key key) const {
// find value with key
return value;
}
Value& search(Key key) {
return utility::remove_const(notstd::as_const(*this).search(key));
}
或者:
Value& const search(Key key) const {
return search(*this, key);
}
Value& search(Key key) {
return search(*this, key);
}
private:
template<class Self>
friend decltype(auto) search(Self& self, Key key){
// find value with key
}
我们将工作委托给朋友模板,其中 self
可能是常量。
const_cast 能否用于创建已实现方法的非常量版本?我想我看到了一些类似的东西(建议使用 const 方法来完成实际工作),但我不太确定它应该如何工作。
Value& const search(key) const {
// find value with key
return value;
}
Value& search(key) {
return const_cast<Value&>(search(key));
}
如果不是这样,创建没有代码重复的非常量函数的推荐方法是什么?
最简单的方法是使用 C++17 中的 as_const
:
Value& search(key) {
return const_cast<Value&>(std::as_const(*this).search(key));
}
没有它你也可以这样做(或者自己实现,不是很难)
Value& search(key) {
return const_cast<Value&>(static_cast<const T&>(*this).search(key));
}
其中 T
是您的 class 的类型(您可以使用 decltype
的通用解决方案,但由于 decltype(*this)
是引用类型,它变得非常难看).
您可以查看 as_const
实现 here or the generic cast here。
两种方法。
第一个:
namespace notstd{ // backported C++17
template<class T>
T const& as_const(T& t){return t;}
template<class T>
T const&& as_const(T&& t){return t;}
}
namespace utility { // not ever in std
template<class T>
T& remove_const(T const& t){return const_cast<T&>(t);}
template<class T>
T&& remove_const(T const&& t){return const_cast<T&&>(t);}
}
然后:
Value& const search(Key key) const {
// find value with key
return value;
}
Value& search(Key key) {
return utility::remove_const(notstd::as_const(*this).search(key));
}
或者:
Value& const search(Key key) const {
return search(*this, key);
}
Value& search(Key key) {
return search(*this, key);
}
private:
template<class Self>
friend decltype(auto) search(Self& self, Key key){
// find value with key
}
我们将工作委托给朋友模板,其中 self
可能是常量。