[英]Deducing the types
I am trying to understand type deduction while walking through Scott Meyer's Effective Modern C++. 我在遍历Scott Meyer的《 Effective Modern C ++》时试图理解类型推导。
Consider the code snippet below: 考虑下面的代码片段:
template<typename T>
void f(const T& param); // param is now a ref-to-const; paramType is const T&
int x = 27; // as before
const int cx = x; // as before
const int& rx = x; // as before
f(x); // T is int, param's type is const int&
f(cx); // T is int, param's type is const int&
f(rx); // T is int, param's type is const int&
He says that since the paramType
is a reference, we can follow a two step procedure to deduce the type of T
: 他说,由于paramType
是引用,因此我们可以按照两步过程来推导T
的类型:
expr
(ie, x
, cx
and rx
) 忽略expr
引用(如果有的话)(即x
, cx
和rx
) expr
and paramType
模式匹配expr
和paramType
的类型 Now when cx
is a const int
: 现在,当cx
是const int
:
cx -> const int cx-> const int
paramType -> reference to const int paramType->引用const int
So, according to the logic mentioned, shouldn't T
be a const int
due to pattern matching (and not just int
)? 因此,根据所提到的逻辑,由于模式匹配(而不仅仅是int
), T
不应该是const int
吗? I understand that the const
ness of cx
has been passed over to paramType
, but is what he says, wrong? 我知道cx
的const
已经传递给paramType
,但是他说的是对的吗? Is this 2 step procedure that he has mentioned not to be followed as a rule of thumb? 根据经验,他提到的这两个步骤是否遵循? How do you do it? 你怎么做呢?
Thanks! 谢谢!
In his book Scott uses this "notation": Scott在他的书中使用了这种“符号”:
template<typename T>
void f(ParamType param); // where `ParamType` depends on T
So let's do pattern matching for ParamType
when param
is const int
. 因此,当param
为const int
时,让我们为ParamType
进行模式匹配。 We have: 我们有:
const T & <----> const int // <----> is symbolic notation for pattern matching
So T
is deduced as int
, hence ParamType
is const int&
. 因此T
推导为int
,因此ParamType
为const int&
。
当cx
为const int
,则T
推导为int
因此const T& param
为const int& param
,即param
为const int&
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.