1

我在浏览 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

  1. expr忽略(即xcxrx)中的引用(如果有)
  2. 模式匹配的类型exprparamType

现在cx是什么时候const int

cx -> 常量整数

paramType -> 对 const int 的引用

那么,根据提到的逻辑,不T应该是const int由于模式匹配(而不仅仅是int)?我知道 的constnesscx已经传递给paramType,但他所说的是否有误?他提到的这个两步程序是否作为经验法则不能遵循?你怎么做呢?

谢谢!

4

2 回答 2

3

他的书中,斯科特使用了这个“符号”:

template<typename T>
void f(ParamType param); // where `ParamType` depends on T

ParamType所以让我们对when paramis进行模式匹配const int。我们有:

const T & <----> const int // <----> is symbolic notation for pattern matching

所以T推导出为int,因此ParamTypeconst int&

于 2017-03-27T22:40:21.793 回答
1

cxis时const int, then被T推断为is , ie is of type 。intconst T& paramconst int& paramparamconst int&

于 2017-03-27T22:29:25.630 回答