by feng
Variadic Templates 的引入,消去了烦冗的模板特化。
一个例子:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#include
double
do_sum()
{
return
0;
}
template
<
typename
T,
typename
... Args >
double
do_sum( T&& t, Args&& ... args )
{
return
t + do_sum( args... );
}
int
main()
{
std::cout << do_sum( 1.0, 2.0, 3.0, 4.0 )
<< std::endl;
return
0;
}
|
这里需要注意的有两点:
- double do_sum() 这个函数必须在变长模板函数 double do_sum( T&& t, Args&& … args ) 之前声明
- 变长模板函数实现中必须使用另外一个函数递归实现
另外要看到,在变长模板函数声明中使用 … 的方法
- 模板上用的是 template< typename… Args>
- 函数参数中用的是 double do_sum(Arg … arg)
- 函数体中用的是 do_sum(arg…)
大致可以看出,有 typename 的时候 .. 跟 typename 后边,否则跟在 Arg 后边,最后则是在参数 arg 后边
如果需要知道到底传入了多少个参数可以这样来
|
1
2
3
4
5
|
template
<
typename
... Args>
std::
size_t
how_many_args(Args ... args)
{
return
sizeof
...(args);
}
|
variadic template 基本使用到这里就差不多了,下边的内容略略而过即可
再次注意这个 …,来个稍微有点复杂的
|
1
2
3
4
5
6
7
8
|
template
<
typename
... T>
void
f(T (* ...t)(
int
,
<script type="text/java script">
|




