程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 《Effective Modern C++》Item 1總結,effectivemodernc

《Effective Modern C++》Item 1總結,effectivemodernc

編輯:C++入門知識

《Effective Modern C++》Item 1總結,effectivemodernc


Item 1: Understand template type deduction. 理解模板類型推導

template<typename T> void f(ParamType param);


The type deduced for T is dependent not just on the type of expr, but also on the form of ParamType.

對於T類型推導,不僅依賴傳入模板表達式也依賴ParamType的形式。

  •  ParamType is a pointer or reference type, but not a universal reference. (Universal references are described in Item 24. At this point, all you need to know is that  they exist and that they’re not the same as lvalue references or rvalue references.)如果ParamType形式是一個指針或引用,並且不是全球通引用,全球通引用將在條款24介紹

  • ParamType is a universal reference.ParamType形式是全球通引用。

  • ParamType is neither a pointer nor a reference.ParamType形式既不是指針也不是引用。

Case 1: ParamType is a Reference or Pointer, but not a Universal Reference

template<typename T>
void f(T& param); // param is a reference

int x = 27; // x is an int
const int cx = x; // cx is a const int
const int& rx = x; // rx is a reference to x as a const int

f(x);  // T is int, param's type is int&
f(cx); // T is const int,
       // param's type is const int&
f(rx); // T is const int,
       // param's type is const int&

 

template<typename T>
void f(const T& param); // param is now a ref-to- const
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形式是一個指針或指向const對象的指針,情況基本差不多。

template<typename T> void f(T* param);
int x= 27;
const int *px = &x; // px is a ptr to x as a const int
const int * const cpx= &x;
f(&x); // T is int, param's type is int*
f(px); // T is const int,
 // param's type is const int*
f(cpx);// T is const int,
     // param's type is const int*

 


Case 2: ParamType is a Universal Reference

 

Case 3: ParamType is Neither a Pointer nor a Reference

template<typename T> void f(T param);
int x = 27; // as before
const int cx = x; // as before
const int& rx = x; // as before
f(x); // T's and param's types are both int
f(cx); // T's and param's types are again both int
f(rx); // T's and param's types are still both int

還有頂層const需要忽略,而底層const保留

template<typename T>
void f(T param); // param is still passed by value
const char* const ptr = // ptr is const pointer to const object
 "Fun with pointers";
f(ptr); // pass arg of type const char * const

T,param type is const char*

寫到這裡吧,本來想翻譯這本書,翻譯一段,就只想翻譯Item1,翻譯Item1一半,我放棄了,原諒我吧。

向大家推薦這麼書,裡面有42條款,這麼書作者是大名鼎鼎《Effective C++》 Scotter Meyer寫的,主要講C++11/14,與時俱進嘛。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved