1、可变参数的函数模板
#include<iostream>
#include<bitset>
void printFun()
{}
template <typename T, typename... Types>
void printFun(const T& firstArg, const Types&... args)
{
std::cout << firstArg << std::endl;
std::cout << sizeof...(args) << std::endl;
printFun(args...);
}
int main(int argc, char** argv)
{
printFun(100.100, "hello world", std::bitset<16>(888), 999);
}
运行结果如下
100.1
3
hello world
2
0000001101111000
1
999
0
2、可变参数的函数模板
#include<iostream>
template<typename... Values>
class myTuple;
template<> class myTuple<> {
};
template <typename Head, typename... Tail>
class myTuple<Head, Tail...> : private myTuple<Tail...>
{
typedef myTuple<Tail...> inherited;
public:
myTuple(){};
myTuple(Head v, Tail... vtail):m_head(v), inherited(vtail...){
}
Head head()
{
return m_head;
}
inherited& tail()
{
return *this;
}
private:
Head m_head;
};
int main(int argc, char** argv)
{
myTuple<int, float, std::string> t(41, 3.14, "hello");
std::cout << t.head() << std::endl;
std::cout << t.tail() << std::endl;
}
运行结果
41
3.14