C++ Templates读书笔记< 二 > Tricky Basics
* 关键字typename,用来说明某个标志符是个型别.
eg:
1
template
<
typename T
>
2
class
MyClass
3
{
4
typename T::SubType
*
ptr;
5

6
};
* assignment运算的template版本并不会取代default assignment运算
* 双重模板参数: Template Template Parameters
eg:
1
template
<
typename T,
2
template
<
typename ELEM
3
typename ALLOC
=
std::alloctator
<
ELEM
>
>
4
class
CONT
=
std::deque
5
>
6
class
Stack
7
{
8
COUT
<
T
>
elems;
//
以第一个参数的型别完成了实例化,
也可以利用class template内的任何型别 来实例化
10
};
11
//
注:template template arguments必须完全匹配对应的参数。预设的template arguments会被编译器忽略。
12
// 所以,如果上面没有写 typename ALLOC
=
std::alloctator
<
ELEM
>
就会报错
function templates 不允许拥有template template parameters
* 初始化
eg:
1
template
<
typename T
>
2
class
MyClass
3
{
4
private
:
5
T x;
6
public
:
7
MyClass()
8
: x()
//
即使T为build-in type,x也可以被初始化
9
{
10
}
11
};
* 只有by value传参时,才会发生 array to pointer 的转换
eg:
1
template
<
typename T
>
2
inline T
const
&
max( T
const
&
a, T
const
&
b )
3
{
4
return
a
<
b
?
b : a;
5
}
6
7
max(
"
apple
"
,
"
peach
"
);
//
ok
8
max(
"
apple
"
,
"
tomato
"
);
//
error, 型别不同,一个是char const[6],一个是char const[7]
9
10
template
<
typename T
>
11
inline T max( T a, T b )
12
{
13
return
a
<
b
?
b : a;
14
}
15
16
max(
"
apple
"
,
"
peach
"
);
//
ok
17
max(
"
apple
"
,
"
tomato
"
);
//
ok, 发生了array to pointer的转换, 但比较结果是错的,因为实际上比较的是指针地址