繁体   English   中英

使用const_cast创建方法的非const变体

[英]Using const_cast for creating non-const variant of methods

const_cast可以用于创建已实现方法的非const版本吗? 我想我沿这些思路看了一些(建议使用const方法进行实际工作),但是我不确定该如何工作。

Value& const search(key) const {
    // find value with key
    return value;
}

Value& search(key) {
    return const_cast<Value&>(search(key));
}

如果不是这种方式,那么在没有代码重复的情况下创建非const函数的推荐方式是什么?

最简单的方法是使用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是您的类的类型(您可以使用带有decltype的通用解决方案,但是由于decltype(*this)是引用类型,所以它确实很难看)。

你可以看看的as_const实现这里或通用投在这里

两种方法。

第一:

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM