這段時間在通過"C++Templates The Complete Guide"這本書學習Templates。發現這本書確實不錯:語言簡明,內容翔實。特別是每章后面的Summery總結得很好。這份讀書筆記就已這個Summery為基礎寫的。
書前面的Prefece和Chapter 1就跳過了。既然來學習Templates就已經知道它的重要性了。
??????????????????????????????? Chapter 2 FunctionTemplates
1. Function templates define a family of functions for different template arguments;
template?
<
typename?T
>
inline?T?
const
&
?max?(T?
const
&
?a,?T?
const
&
?b)

{
????
//
?if?a?<?b?then?use?b?else?use?a
????
return
??a?
<
?b?
?
?b?:?a;
}
2. When you pass template arguments, function templates are instantiated for these argument types.
The process of replacing templates parameters by concrete types is called instantiatin.(at compiled time)
3. You can explicitly qualify the template parameters
{
//
?because?no?automatic?type?conversion?if?allowed?in?templates,so
max(static_cast
<
double
>
(
4
),
4.2
)
//
cast?the?arguments?so?that?they?both?match
max
<
double
>
(
4
,
4.2
)
//
?specify?explicitly?the?type?of?T
}
4. You can overload funciton templates
inline?
int
?
const
&
?max?(
int
?
const
&
?a,?
int
?
const
&
?b)?

{
????
return
??a?
<
?b?
?
?b?:?a;
}
//
?maximum?of?two?values?of?any?type
template?
<
typename?T
>
inline?T?
const
&
?max?(T?
const
&
?a,?T?
const
&
?b)

{
????
return
??a?
<
?b?
?
?b?:?a;
}
//
?maximum?of?three?values?of?any?type
template?
<
typename?T
>
inline?T?
const
&
?max?(T?
const
&
?a,?T?
const
&
?b,?T?
const
&
?c)

{
????
return
?::max?(::max(a,b),?c);
}
int
?main()

{
????::max(
7
,?
42
,?
68
);?????
//
?calls?the?template?for?three?arguments
????::max(
7.0
,?
42.0
);?????
//
?calls?max<double>?(by?argument?deduction)
????::max(
'
a
'
,?
'
b
'
);??????
//
?calls?max<char>?(by?argument?deduction)
????::max(
7
,?
42
);?????????
//
?calls?the?nontemplate?for?two?ints
????::max
<>
(
7
,?
42
);???????
//
?calls?max<int>?(by?argument?deduction)
????::max
<
double
>
(
7
,?
42
);?
//
?calls?max<double>?(no?argument?deduction)
????::max(
'
a
'
,?
42.7
);?????
//
?calls?the?nontemplate?for?two?ints
}
ps: the overload resolution process normally prefers this nontemplate over one generated from the template. the fourth call falls under this rule.
5. When you overload function templates, limit your changes to specifying template parameters explicitly
{
max
<>
(
7
,
42
);
//
call?max<int>?(by?argument?deduction)
}
6. Make sure you see all overloaded versions of funciton templates before you call them
template?
<
typename?T
>
inline?T?
const
&
?max?(T?
const
&
?a,?T?
const
&
?b)

{
????
return
??a?
<
?b?
?
?b?:?a;
}
//
?maximum?of?three?values?of?any?type
template?
<
typename?T
>
inline?T?
const
&
?max?(T?
const
&
?a,?T?
const
&
?b,?T?
const
&
?c)

{
????
return
?max?(max(a,b),?c);??
//
?uses?the?template?version?even?for?ints
}
??????????????????????????????
//
?because?the?following?declaration?comes
???????????????????????????????
//
?too?late:
//
?maximum?of?two?int?values
inline?
int
?
const
&
?max?(
int
?
const
&
?a,?
int
?
const
&
?b)?

{
????
return
??a?
<
?b?
?
?b?:?a;
}
?