模板类型推导

模板类型基本形如以下:

template
		void f(ParamType param);

调用类似于下:

f(expr); // call f with some expression

类型推导分以下三种情况:

  1. 当ParamType是引用或者指针,不是右值引用时
    a)如果表达式是引用,那么忽略引用部分
    例如:
template
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
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&
template
void f(T* param); 				// param is now a pointer
int x = 27; 					// as before
const int *px = &x; 			// px is a ptr to x as a const int
f(&x); 							// T is int, param's type is int*
f(px); 							// T is const int,
								// param's type is const int*
  1. 当ParamType是右值引用时
    a)如果表达式是左值,那么T和ParamType都被推导为左值引用
    b)如果表达式是右值,那么可按1规则推导
    例如:
template
void f(T&& param); 		   	 // param is now a universal reference
int x = 27;					 // as before
const int cx = x; 			 // as before
const int& rx = x; 			 // as before
f(x); 						 // x is lvalue, so T is int&,
							 // param's type is also int&
f(cx);						 // cx is lvalue, so T is const int&,
							 // param's type is also const int&
f(rx); 						 // rx is lvalue, so T is const int&,
							 // param's type is also const int&
f(27); 						 // 27 is rvalue, so T is int,
							 // param's type is therefore int&&
  1. 当ParamType既不是指针也不是引用时
    a)如果表达式是引用,那么忽略引用
    b)除引用外,如果还有const,volatile,那么一样都忽略。
    例如:
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

.
c)如果是指针,则推导为指针的类型
d)如果是数组,则推导为指针的类型
e)如果为函数类型
如:

void someFunc(int, double); 		// someFunc is a function;
									// type is void(int, double)
template
void f1(T param); 					// in f1, param passed by value
template
void f2(T& param); 					// in f2, param passed by ref
f1(someFunc); 						// param deduced as ptr-to-func;
									// type is void (*)(int, double)
f2(someFunc); 						// param deduced as ref-to-func;
									// type is void (&)(int, double)

你可能感兴趣的:(c++,模板类型推导)