【发布时间】:2017-03-27 22:21:54
【问题描述】:
我在浏览 Scott Meyer 的 Effective Modern C++ 时试图理解类型推导。
考虑下面的代码 sn-p:
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 -> 常量 int
paramType -> 对 const int 的引用
那么,根据上面提到的逻辑,由于模式匹配,T 不应该是const int(而不仅仅是int)吗?我知道cx 的constness 已经传递给paramType,但他说的有错吗?他提到的这个两步程序是否作为经验法则不能遵循?你是怎么做到的?
谢谢!
【问题讨论】:
-
你歪曲了一些东西。
paramType是什么? -
@KerrekSB,它是
const T&。我已将其包含在 cmets 中(在代码的第二行)。 -
不要使用 cmets。仅参考实际代码中的内容。我不知道评论是什么意思。改为“
param的类型”。 -
如果您将
const T&解释为“const引用T”而不是“引用const T”,则更容易理解。const实体只能绑定到const引用,但非 cv 实体可以绑定到const和非const引用。 -
在大多数情况下,它们实际上是相同的(
const对int的引用实际上将int视为const,无论是否相同),但并非总是如此(对于例如,when working with references to pointers;const int*&是对const int*的非 cv 引用,但int* const&是对const的引用int*,这与指向const int的指针之间的语法差异相同(const int*) 和一个指向int(int* const) 的const指针。
标签: c++ c++11 effective-c++