【发布时间】:2018-03-05 08:11:21
【问题描述】:
我写了一个可变参数模板来递归打印所有参数:
#include <iostream>
using std::ostream; using std::istream;
using std::cin; using std::cout; using std::endl;
template <typename T, typename... Args>
ostream &myprint(ostream &os, const T &t, const Args&... rest) {
if (sizeof...(rest)) {
os << t << ", ";
return myprint(os, rest...);
}
else
return os << t;
}
int main(int argc, char *argv[]) {
myprint(cout, "hello");
return 0;
}
但是当我用g++ -std=c++1y 编译它时,它会抱怨:
error: no matching function for call to ‘myprint(std::ostream&)’
return myprint(os, rest...);
在函数myprint 中,我检查了sizeof...(rest) 的值。而当为0时,不会调用myprint(os, rest...)。所以我不知道为什么它会调用myprint(std::ostream&)。
我也搜索了相关的问题,我发现它需要一个基本案例。但是为什么我需要一个基本案例,而sizeof... 不能在可变参数模板中工作?
对于简单的不定递归情况:
template <typename T, typename... Args>
ostream &myprint(ostream &os, const T &t, const Args&... rest) {
os << t << ", "; // print the first argument
return print(os, rest...); // recursive call; print the other arguments
}
上面的代码根本无法编译同样的错误。
【问题讨论】:
标签: c++ c++11 templates recursion variadic-templates