《Effective Modern C++》Item 1总结

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

  1. 如果传入表达式是一个引用,T忽略其引用部分
  2. 然后模式匹配表达式类型与ParamType形式,继而推导T的类型
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

  1. 如果传入模板表达式是左值,那么T和ParamType均会推导为左值引用,这里使用引用折叠语法。
  2. 如果传入模板表达式是右值,那么T类型推导遵循case1规则。

 

Case 3: ParamType is Neither a Pointer nor a Reference

template<typename T> void f(T param);
  1. 如果传入模板表达式类型是引用,T的类型忽略引用。
  2. 如果表达式剩余部分是const,T也忽略掉,是volatile,T也忽略掉。
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,与时俱进嘛。

你可能感兴趣的:(effective)