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形式是全球通引用。
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,与时俱进嘛。