0%

C++模板

C++模板推导规则

模板推导规则

1
2
3
4
template<typename T>
void f(ParamType param);

f(expr); // deduce T and ParamType from expr

在编译期间,编译器通过expr推导T和ParamType的类型。直觉上,T的类型总是与expr一致,然而实际上,T的类型推到结果,不仅仅依赖于expr的类型,还取决于ParamType的形式。

ParamType 可以写为 T& / T&& / T* 分为为 引用/万能引用/指针

指针或引用

若expr是引用(左值引用或右值引用),则先将引用部分忽略;然后,对expr的类型和ParamType的类型进行模式匹配,来决定T的类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
template<typename T>
void f(const T& param); // ParamType 为左值引用的形参

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

const int y = 28;
f(y); // T is int, param's type is const int&

int &&rr = 27;
f(rr); // T is int, param's type is const int&

const int &&crr = 28;
f(crr); // T is int, param's type is const int&

int *p = &x;
const int *cp = &x;
const char * const ccp = "abcd";
f(p); // T is int*, param's type is int* const &
f(cp); // T is const int*, param's type is const int* const &
f(ccp); // T is const char*, param's type is const char* const &

f(27); // T is int, param's type is const int &