두 가지 접근법.
첫째 :
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));
}
나 : 우리는 self
어쩌면 const가있는 친구 템플릿에 작업을 위임
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
}
.
먼저 "중복성"이라는 단어를 찾아보십시오. 그것은 "복제"를 의미하지 않습니다. 기다려. 알았어. const를 캐스팅하는 것은 당신이 나쁜 처지에서 그리고 마감 시간까지 자신을 발견했을 때만하는 일입니다. 예외가 있습니다. 예를 들어, 클래스가 공용에 대해 투명한 캐시를 가지고있는 경우. const가 언어에 도입되었을 때, "const"가 정말로, 실제로는 상수인지, 아니면 "마치"상수인지에 대한 논쟁이있었습니다. "것처럼"이겼고, 따라서 const를 던지면서 const가 탄생했습니다. –
관련 : https://stackoverflow.com/q/123758/1896169 – Justin