自动类型推导中的 Const
Const in auto type deduction
我正在阅读 Scott Meyers 的 Effective modern C++。项目 1 包含以下示例:
template<typename T>
void f(T& param); // param is a reference
int x = 27; // x is an int
const int cx = x; // cx is a const int
f(cx); // T is const int,
// param's type is const int&
项目 3 中出现以下示例:
Widget w;
const Widget& cw = w;
auto myWidget1 = cw; // auto type deduction:
// myWidget1's type is Widget
根据第 1 项,我预计 myWidget1
的类型为 const Widget
。我错过了什么吗?
在大多数情况下auto
遵循模板参数推导规则:
§ 7.1.6.4 [dcl.spec.auto]/p6:
Once the type of a declarator-id has been determined according to 8.3, the type of the declared variable
using the declarator-id is determined from the type of its initializer using the rules for template argument
deduction. Let T
be the type that has been determined for a variable identifier d
. Obtain P
from T
by
replacing the occurrences of auto
with either a new invented type template parameter U
or, if the initializer
is a braced-init-list (8.5.4), with std::initializer_list<U>
. The type deduced for the variable d
is then the deduced A
determined using the rules of template argument deduction from a function call (14.8.2.1).
§ 14.8.2.1 [temp.deduct.call]/p2:
If P
is not a reference type:
[...]
If A
is a cv-qualified type, the top level cv-qualifiers of A
's type are ignored for type deduction.
如果你想让myWidget1
是const Widget&
类型,应该声明为引用类型,例如:
auto& myWidget1 = cw;
// ^
auto myWidget1 = cw;
遵循Meyers书中模板参数类型推导的第三条规则,即按值传递。
当您按值传递时,cv 限定符和引用将被忽略,因为您正在获取该对象的新副本,因此您并不真正关心您从中复制的旧对象是 const 还是引用。
我正在阅读 Scott Meyers 的 Effective modern C++。项目 1 包含以下示例:
template<typename T>
void f(T& param); // param is a reference
int x = 27; // x is an int
const int cx = x; // cx is a const int
f(cx); // T is const int,
// param's type is const int&
项目 3 中出现以下示例:
Widget w;
const Widget& cw = w;
auto myWidget1 = cw; // auto type deduction:
// myWidget1's type is Widget
根据第 1 项,我预计 myWidget1
的类型为 const Widget
。我错过了什么吗?
在大多数情况下auto
遵循模板参数推导规则:
§ 7.1.6.4 [dcl.spec.auto]/p6:
Once the type of a declarator-id has been determined according to 8.3, the type of the declared variable using the declarator-id is determined from the type of its initializer using the rules for template argument deduction. Let
T
be the type that has been determined for a variable identifierd
. ObtainP
fromT
by replacing the occurrences ofauto
with either a new invented type template parameterU
or, if the initializer is a braced-init-list (8.5.4), withstd::initializer_list<U>
. The type deduced for the variabled
is then the deducedA
determined using the rules of template argument deduction from a function call (14.8.2.1).
§ 14.8.2.1 [temp.deduct.call]/p2:
If
P
is not a reference type:
[...]
If
A
is a cv-qualified type, the top level cv-qualifiers ofA
's type are ignored for type deduction.
如果你想让myWidget1
是const Widget&
类型,应该声明为引用类型,例如:
auto& myWidget1 = cw;
// ^
auto myWidget1 = cw;
遵循Meyers书中模板参数类型推导的第三条规则,即按值传递。
当您按值传递时,cv 限定符和引用将被忽略,因为您正在获取该对象的新副本,因此您并不真正关心您从中复制的旧对象是 const 还是引用。