[英]Deducing the types
我在遍历Scott Meyer的《 Effective Modern C ++》时试图理解类型推导。
考虑下面的代码片段:
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&
他说,由于paramType
是引用,因此我们可以按照两步过程来推导T
的类型:
expr
引用(如果有的话)(即x
, cx
和rx
) expr
和paramType
的类型 现在,当cx
是const int
:
cx-> const int
paramType->引用const int
因此,根据所提到的逻辑,由于模式匹配(而不仅仅是int
), T
不应该是const int
吗? 我知道cx
的const
已经传递给paramType
,但是他说的是对的吗? 根据经验,他提到的这两个步骤是否遵循? 你怎么做呢?
谢谢!
Scott在他的书中使用了这种“符号”:
template<typename T>
void f(ParamType param); // where `ParamType` depends on T
因此,当param
为const int
时,让我们为ParamType
进行模式匹配。 我们有:
const T & <----> const int // <----> is symbolic notation for pattern matching
因此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.