【发布时间】:2015-02-27 22:15:57
【问题描述】:
以下代码显示,如果使用引用类型(例如,int&)实例化采用 ref-to-const 参数的模板,则该参数不是 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&。如果是这样,就标准而言,这究竟是如何发生的?如果这不是发生了什么,那是什么?
【问题讨论】:
-
www-01.ibm.com/support/knowledgecenter/SS2LWA_12.1.0/… 有 2 个表用于参考折叠。
-
相关/重复:Reference collapsing?
标签: c++ templates type-deduction