【发布时间】:2013-10-27 00:57:49
【问题描述】:
这是一个打印参数的可变参数模板。
#include <string>
#include <iostream>
void Output() {
std::cout<<std::endl;
}
template<typename First, typename ... Strings>
void Output(First arg, const Strings&... rest) {
std::cout<<arg<<" ";
Output(rest...);
}
int main() {
Output("I","am","a","sentence");
Output("Let's","try",1,"or",2,"digits");
Output(); //<- I do not want this to compile, but it does.
return 0;
}
有没有办法在没有“无参数”调用工作的情况下获得此功能,并且不必每次都编写两个函数?
【问题讨论】:
-
你可以写一个单参数版本而不是零参数版本。您可以将两者都隐藏在命名空间中,并通过需要 > 0 个参数的函数调用它们。
-
我回答了您的问题,但我不确定您所说的“不必每次都编写两个函数”是什么意思?
标签: function templates c++11 parameters variadic-templates