Can the const_cast be used for creating non-const versions of already implemented methods? I think I saw something along these lines (with recommendation for the const method to do the actual work), but I'm not really sure how it's supposed to work.
Value& const search(key) const {
// find value with key
return value;
}
Value& search(key) {
return const_cast<Value&>(search(key));
}
If not this way, what is recommended way of creating non-const functions without code duplicity?
The easiest way to do it is with as_const
from C++17:
Value& search(key) {
return const_cast<Value&>(std::as_const(*this).search(key));
}
Without it you can do this instead (or implement it yourself, it's not very hard)
Value& search(key) {
return const_cast<Value&>(static_cast<const T&>(*this).search(key));
}
Where T
is the type of your class (you can have a generic solution with decltype
but it gets really ugly due to decltype(*this)
being a reference type).
You can take a look at the as_const
implementation here or the generic cast here .
Two approaches.
First:
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);}
}
then:
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));
}
or alternatively:
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
}
where we delegate the work to a friend template where self
is maybe-const.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.