问题描述
以下代码显示,如果使用引用类型(例如int&
)实例化带有ref-to- const
参数的模板,则该参数不是const
:
The following code shows that if a template taking a ref-to-const
parameter is instantiated with a reference type (e.g., int&
), the parameter isn't const
:
#include <iostream>
template<typename T>
void f(const T& arg) // arg isn't const if T is a reference type
{
arg = -1;
}
int main()
{
int x = 0;
f<int&>(x); // instantiate f with reference type
std::cout << x << '\n'; // prints -1 under gcc, clang, and msvc
}
这是怎么回事?
我的猜测是arg
的初始类型是int & const &
,并且以某种方式转换为int&
.如果是这样的话,那么就标准而言,这究竟是怎么发生的呢?如果这不是怎么回事,那是什么?
My guess is that the initial type of arg
is int & const &
and that this somehow transforms to int&
. If that's so, exactly how does that happen, in terms of the standard? If that's not what's going on, what is?
推荐答案
感谢来自莫斯科的弗拉德对 C ++的答案:具有显式的模板函数指定引用类型作为类型参数,我相信const
-disappearance的关键是8.3.2/1,它表示:
Thanks to Vlad from Moscow's answer to C++: template function with explicitly specified reference type as type parameter, I believe the crux of the const
-disappearance is 8.3.2/1, which says:
我已经整理了相关文字. (我想按照标准格式设置整个段落的格式,但是我不知道如何获得正确的缩进和添加下标.)
I've emboldened the relevant text. (I'd like to format the entire paragraph as it is in the standard, but I can't figure out how to get the right indentation and to add subscripting.)
const
消失后,正常的参考折叠就会像往常一样出现.
Once the const
disappears, normal reference collapsing kicks in as usual.
这篇关于为什么在const T&中使用const? T是引用类型时参数消失吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!