且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么C ++ const引用可以归类为非const引用

更新时间:2023-11-11 22:43:52


引用规则折叠会导致这种行为吗?

Is it a rule of reference collapsing that causes this behaviour?

。您有:

T = int&
const T& = const (int&) &

引用不能为 const (您仍然无法重新绑定它们,因此将其忽略),对引用的引用只是引用。

References can't be const (you can't rebind them anyways, so it's ignored) and a reference to a reference is just a reference.

所以您拥有

const T& = int&

要解决此问题,您需要应用 const 到基础类型,您可以通过删除引用来实现:

To fix this, you need to apply const to the underlying type, which you can do like this by removing the reference:

const std::remove_reference_t<T>& get() { return x_; }
//    ^^^^^^^^^^^^^^^^^^^^^^^