1. 数量不定的模板参数(variadic templates)
先看图:
这里的流程是:
- 调用
这里先调用模板函数, 也就是上图2中的函数, 这里第一次print(7.5, "hello", bitset<16>(377), 42);
firstArg
是7.5
, 然后就输出7.5
, 接着下面的语句:
这里递归调用print, 相当于:print(args...);
接下来同理, 直到最后一个print("hello", bitset<16>(377), 42);
42
最后一个42
的调用流程是, 当输出42
时, 然后继续调用print
, 但是要注意, 这时调用的print
是上图第一个print
, 也即什么都没干的print
.
1.1 用sizeof…(args)查看参数的数量
代码:
#include <iostream>
#include <bitset>
using namespace std;
void print(){
}
template<typename T, typename... Types>
void print(const T& first_arg, const Types&... args){
cout << first_arg << endl;
print(args...);
cout << sizeof...(args) << endl;
}
int main(){
print(7.5, "hello", bitset<16>(377), 42);
return 0;
}
输出:
7.5
hello
0000000101111001
42
0
1
2
3
上面输出之所以是0 1 2 3
是因为函数的递归调用, 为0
是因为递归到最底层了, 所以参数数量为0
, 其他的类比可推.