问题
I was playing with C++ template type deduction and managed to compile this little program.
template<typename T>
void f(const T& val)
{
val = 1;
}
int main()
{
int i = 0;
f<int&>(i);
}
It compiles on all major compilers but I do not understand why. Why can f
assign to val
, when val
is explicitly marked const
? Is it bug in these compilers or is it valid behavior according to the C++ standard?
回答1:
§8.3.2 [dcl.ref]/p6:
If a typedef-name (7.1.3, 14.1)* or a decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a type T, an attempt to create the type “lvalue reference to cv TR” creates the type “lvalue reference to T”, while an attempt to create the type “rvalue reference to cv TR” creates the type TR.
This is known as reference collapsing and is introduced in C++11. In C++03, your code would be ill-formed, but some compilers supported it as an extension.
Note that in const T &
, the const
applies to the type T
, so when T
is int &
, the const
would apply to the reference type itself (which is meaningless as references are immutable anyway), not the type referred to. This is why the reference collapsing specification ignores any cv-qualifiers on TR
.
*A template type parameter is a typedef-name, per §14.1 [temp.param]/p3:
A type-parameter whose identifier does not follow an ellipsis defines its identifier to be a typedef-name (if declared with
class
ortypename
) or template-name (if declared withtemplate
) in the scope of the template declaration.
回答2:
I would like to append other posts with the following quote from the C++ Standard (8.3.2 References)
1... Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name (7.1.3, 14.1) or decltype-specificer (7.1.6.2), in which case the cv-qualifiers are ignored.
[ Example:
typedef int& A;
const A aref = 3; // ill-formed; lvalue reference to non-const initialized with rvalue
In the example above from the C++ Standard the last statement will not be compiled because qualifier const is ignored (according to the quote) and you may not bind rvalue with a non-const reference.
回答3:
const T&
does not turn into int&
in this example: in f<int&>(i)
, you are explicitly setting T
to int&
. const
only enters the picture when that definition of T
is used to determine the type of val
, which becomes const int&
(one subtlety there is that references are collapsed during this substitution, so you don't wind up with two &
's in the type).
来源:https://stackoverflow.com/questions/27256516/c-template-function-with-explicitly-specified-reference-type-as-type-paramete