[英]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.