簡體   English   中英

推導類型

[英]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的類型:

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

現在,當cxconst int

cx-> const int

paramType->引用const int

因此,根據所提到的邏輯,由於模式匹配(而不僅僅是int ), T不應該是const int嗎? 我知道cxconst已經傳遞給paramType ,但是他說的是對的嗎? 根據經驗,他提到的這兩個步驟是否遵循? 你怎么做呢?

謝謝!

Scott在他的書中使用了這種“符號”:

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

因此,當paramconst int時,讓我們為ParamType進行模式匹配。 我們有:

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

因此T推導為int ,因此ParamTypeconst int&

cxconst int ,則T推導為int因此const T& paramconst int& param ,即paramconst int&類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM