forked from shangerxin/BookNotes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathC++ Templates The Complete Guide = Vandevoorde, Josuttis; Note = Erxin.txt
429 lines (373 loc) · 11.5 KB
/
C++ Templates The Complete Guide = Vandevoorde, Josuttis; Note = Erxin.txt
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
C++ Templates The Complete Guide = Vandevoorde, Josuttis; Note = Erxin
:说明
>本书相关网站
http://www.josuttis.com/tmplbook
:基础
>为了更好的格式以及通用性而使用模板
:函数模板
>定义
template <typename T>
inline T const & max(T const& a, T const& b)
{}
>函数模板可以重载
>可以直接调用, 参数类型会推演出来
>模板被编译两次, 实例化之前, 实例化期间
:类模板
>定义
template <typename|class T>
class class_name
{
public:
class_name
{
}
protected:
...
private:
...
};
>模板的特化
template<>
class class_name<some_specify_type>
{...};
>局部特化
开始定义
template<typename t1, typename t2>
class class_name
{...};
//局部特化, 模板具有相同参数
template<typename t1>
class class_name<t1, t1>
{...};
//第二个参数是指定类型
template<typename t1>
class class_name<t1, int>
{...};
//两个模板都是指针类型
tempalte<typename t1, typename t2>
class class_name<t1*, t2*>
{...};
>模板可以指定缺省的类型参数
template<typename t1, typename t2 = default_type>
class class_name
{...};
> 对于引入类型参数的用法如方法模板, 尽量使用typename, 虽然class这时和typename等价
对于模板类中引入另一种模板参数作为非模板类型参数的时候这时候该模板的类型定义必须使用class
template <typename T,
template <class Element,
typename ALLOC = std::allocator<ELEM>
class CONST = std::deque>
class Stack
{..}
此时的class关键字不可以被typename 替代, 由于此时的Element类型参数不会再Stack中使用, 所以等价为
template <typename T,
template <typename, typename> class CONST = std::deque>
class Stack
{...}
: 类模板
> 定义
template <typename T>
class Stack
{
private:
std::vector<T> elements;
public:
void push(T const&);
Stack (Stack<T> const&); // copy function
Stack<T>& operator=(Stack<T> const&); //operator
void pop();
T top() const;
bool empty() contst
{
return elements.empty();
}
}
template <typename T>
void Stack<T>::push(element)
{
elements.push_back(element);
}
> 可以针对不同的类型对模板进行特化, 也就是使用特定类型编写模板
template<>
class Stack<std::string>
{...}
> 模板的参数可以使用default参数
: 非类型模板参数
> 例如对刚才Stack初始化大小的设置, 需要常数参数
template <typename T, int MAXSIZE>
class Stack
{
private:
T element[MAXSIZE];
}
:技巧性基础知识
> typename, 模板内的标示符可以是一个类型
>.template构造,(方法中), ->template(类中) 只有在编译器判断小于号(<)之前, 存在依赖于模板参数的构造的时候才需要使用, 标明参数为依赖于模板参数
void printBitset(std::bitset<N> const& bs)
{
std::cout << bs.template to_string<char, traits<char>, allocator<char>>();
}
> 确认内建类型已经初始化
template <typename T>
class MyClass
{
private:
T x;
public:
MyClass() : x()
...
}
: 模板实战
> typeid来输出一个字符串, 描述了作为参数传递的表达式的类型
> 模板的实现类型
+ 分离模型, exporting template, separation model
使用export关键字, 头文件和源文件分离, 缺点是inline类型不能被export
除了类内定义的内联方法以外
使用标准头文件保证头文件的编译顺序, 提高编译过程, 使用预编译指令来整合包含模型和分离模型
+ 包含模型
+ 显示模型
> 错误信息整理程序
http://www.bdsoft.com/tools/stlfilt.html
> 模板中使用哑代码, 来辅助类型检查, 例如boost库中的concept check library
template <typename T>
inline void ignore(T const&)
{}
tempalte <typename T>
void shell(T const& env)
{
class ShallowChecks{
void deref(T::Index ptr)
{
ignore(*ptr);
}
};
typename T::Index I;
middle(i);
}
> 使用tracer 工具来监控程序运行
: 模板术语
> 类和联合(union) 都被称为类类型(class type), 不加限定的时候通常的类指关键字或者struct引入的类类型(class type), 而类不包含union类型
> 类模板, class template, 该类是一个模板, 代表的是整个类家族的参数化描述
> 模板类, template class
+ 类模板同义词
+ 从模板产生的类
+ 具有一个template-id名称的类
>一处定义原则, one-define rule, ODR
:深入模板
> 模板的普通成员可以是虚函数, 例如析构函数
> 友元, 在模板中可以声明三种友元, 类, 函数, 模板类
friend class className<T>;
:模板的名称
> 名称的分类
+ 名称使用域解析运算符(::), 或者访问运算符(., ->)则成为受限运算符
+ 如果一个名称依赖于模板参数, 称它为依赖型名称
> 名称的分类表
identifier, id(operator-function-id), id(conversion-function-id), id(template-id), id(unqualified-id), id(qualified-id), unqualified name, qualified name, dependent name, nondependent name
> 模板使用中尽量避免 <:标记
> 模板名上使用 :: 来加上全局限定
> 对于模板参数指针中的模板内类型, 引用的时候要使用.template或->template以表明引用的是类型使得后面跟着的<type> 解析正确
> 声明依赖名称, 例如模板派生于另一个模板, 引入基类命名空间内的定义使用
using Base<T>::basefield;
:实例化
> 实例化点, POI, 编译过程可能多次实例化, 但是最终只是首个实例化点被保留
> 显示实例化
template void f<int>(int) throw(int);
:模板实参演绎
> 上下文演绎
> 特殊情况和转型运算符
class S
{
public:
template <typename T, int N> operator T[N]&();
};
void f(int (&)[20]);
void g(S s)
{
f(s);
}
这时使用实参-参数对(A, P)进行类型匹配
> Barton-Nackman方法, 此时大多数编译器不支持函数模板重载, 将操作符定义为类的友元函数
> wrapper函数
class S{};
template<typename T>
class Wrapper
{
private:
T object;
public:
Wrapper(T obj):object(obj){} //可以把T隐私转换类型为Wrapper<T>
friend void f(Wrapper<T> const&a){}
};
int main()
{
S s;
Wrapper<S> w(s);
f(w);
}
:特化与重载
> 只要具有不同的签名, 两个函数可以在同一个程序中同时存在, 签名
+ 非受限函数名
+ 函数名称属于类作用于或者名字空间作用域
+ 函数的const, volatile后者const volatile限定符
+ 函数参数类型
+ 如果函数产生自函数模板, 则包括返回类型, 模板参数, 模板实参
> 如果模板参数不同其他相同可以编译通过, 但是在模板实例化的时候将出现两意性
> 全局特化
template<>
type className<type>::function
: 未来的方向
> 尖括号Hack
typedef std::vector<std::list<int> > LineTable; //其中> >的空格是必须的避免 >>被解析为右移运算符
> 非类型模板实参中不能使用字符串, 浮点数模板实参
:模板与设计
> 多态, dynamic polymorphism
> 模板可以使用静多态, 不同的类模板对相同功能的函数定义相同的名字
> STL
> 动多态, Smalltalk
: trait 与policy
> trait, 用于刻画一个事物的特性
> policy类, 一个接口类, 能够在算法应用一个或多个policy类, 为了某种有益的目的而采取的一系列动作
: 模板与继承, denpendent base class, 依赖基类
> 多次继承的时候使用虚拟继承, 避免基类中定义的重复方法
class DefaultClass: virtual public DefaultBase
{}
> 空基类优化, 当空类作为基类时, 只要不会与同一类型的另一个对象或者对象分配在同一地址, 就不需要为其分配任何空间
class Empty{
typedef int Int;
}
class EmptyToo:public Empty{};
class EmptyThree: public EmptyToo{};
> 成员做基类, 为了节省内存存储空间
> 递归模板模式, curiously recurring template pattern, CRTP
template <typename Derived>
class CuriouseBase{...};
class Curious:public CuriousBase<Curious>{...};
CRTP中有一个非依赖型基类, nondependent base class, 类curious不是模板, 免于依赖基类dependent base class的名字可见性问题
CRTP的本质特性
简单应用是记录某个类的对象构造的总个数, 在基类模板中定义静态变量, 构造析构的时候对其增减
一般地CRTP适用于仅能做成员函数的接口(构造, 析构, 下标运算)的实现提取出来
> 参数化虚拟, 模板定义基类, 传入基类的形参是否函数为虚函数决定了模板中调用的函数行为
:metaprogram, 对一个程序进行编译的意思
> 递归模板实例化, 模板定义使用递归初始化, 定义特例结束递归
> 枚举值和静态常量
+枚举值是真常值,是声明常量表达式的唯一方法, 枚举值没有左值即没有地址
> 结合递归模板, 使用枚举值来计算结果
#ifndef SQRT_HPP
#define SQRT_HPP
template<int N, int LO = 0, int HI = N>
class Sqrt
{
public:
enum{mid = (LO+HI+1)/2};
enum{result = (N<mid*mid) ? Sqrt<N, LO, mid-1>::result: Sqrt<N, mid, HI>::result};
};
template< int N, int M>
class Sqrt<N, M, M>
{
public enum{result=M};
};
#endif //SQRT_HPP
> 使用这种方法扩展循环
> Blitz++, the MTL library, POOMA库都是使用metaprogram来为线性代数提供快速计算程序
: 表达式模板, expression template, P313
> 为了提高效率队指针表达式等进行优化, 提高可读性, 编辑在参数模板中
> 鼓励使用计算的赋值运算来取代单纯的赋值运算符来减少不必要的临时变成
+=, *=
template<class T>
SArray<T>& SArray<T>::operator+= (SArray<T> const& b)
{
for(size_t k = 0; k < size(); ++k){
(*this)[k] += b[k];
}
}
但这种方式还有一定的缺陷
+ 符号不雅观
+ 使用时还是需要临时变量 tmp
- 在模板实参中编码表达式
1.2*x + x*y;
we convert the expression to object
A_Add<A_Mult<A_Scalar<double>, Array<double>>, A_Mult<Array<doube>, Array<double>>>
template<typename T, typename OP1, typename OP2>
class A_Add{
private:
typename A_Traits<OP1>::ExprRef op1;
typename A_Traits<OP2>::ExprRef op2;
public:
A_Add(OP1 const& a, OP2 const& b):op1(a), op2(b){
}
T operator[] (size_t idx) const {
return op1[idx] + op2[idx];
}
size_t size() const{
assert(op1.size() == 0 || op2.size() == 0 || op1.size() == op2.size());
return op1.size() != 0 ? op1.size():op2.size();
}
}
...
: 高级应用程序 P345页
> 类型区分, 使用模板编写类型区分程序
> we wish to write these kinds of code
if(TypeT<T>::IsPtrT){
}
else if(TypeT<T>::IsClassT){
}
- 首先开发一些用于辨认基本类型的模板
template<typename T>
class IsFundaT{
public:
enum{Yes = 0, No = 1};
};
//特化基本类型
#define MK_FUNDA_TYPE(T) \
template<> \
class IsFundaT<T>{ \
public: \
enum{Yes = 1, No = 0}; \
}; \
MK_FUNDA_TYPE(bool)
...
extend to all the fundamental type such as char, wchar_t, ...
+ use the template
tempalte<typename T>
void test(T const& t)
{
if(IsFundaT<T>::Yes){
std::cout << "T is fundamental type" << std::endl;
}
else{
std::cout << "T is no fundamental type" << std::endl;
}
}
class MyClass{
};
int main(){
test(1); //is fundamental
test(MyClass()); // is no fundamental
}
- 辨别组合类型
template<typename T>
class CompoundT{
enum{IsPtr = 0, IsRefT = 0, IsArrayT = 0, IsFuncT = 0, IsPtrMemT = 0};
typedef T BaseT;
typedef T BottomT;
typedef CompoundT<void> ClassT;
};
BaseT, 用于构造模板参数类型T 的(直接)类型
BottomT, 是除去指针,引用和数组之后的用于构造T原始类型
如果T是int**则BaseT将是int*, BottomT is int
: 智能指针
> hoder, trule
> 引用计数
: tuple
> duo
> 可递归duo
: 函数对象和回调
>直接调用
> 函数指针与函数引用
> 成员函数指针
> class类型的仿函数
> 指定仿函数
> 内省
> 函数对象组合
> 值绑定
> 仿函数操作