我在浏览 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 -> 常量整数
paramType -> 对 const int 的引用
那么,根据提到的逻辑,不T应该是const int由于模式匹配(而不仅仅是int)?我知道 的constnesscx已经传递给paramType,但他所说的是否有误?他提到的这个两步程序是否作为经验法则不能遵循?你怎么做呢?
谢谢!