【发布时间】:2012-09-02 18:50:36
【问题描述】:
这个例子使用了一个通用的可变参数模板和函数。我想打印出传递给f的参数:
#include <iostream>
template <typename T>
void print(T t)
{
std::cout << t << std::endl;
}
template <typename...T>
void f(T &&...args)
{
print(args...);
f(args...);
}
int main()
{
f(2, 1, 4, 3, 5);
}
但我收到以下错误:
Compilation finished with errors:<br>
source.cpp: In instantiation of '`void f(T ...)` [with `T = {int, int, int, int, int}`]':<br>
source.cpp:16:20: required from here <br>
source.cpp:10:4: error: no matching function for call to '`print(int&, int&, int&, int&, int&)`'<br>
source.cpp:10:4: note: candidate is:<br>
source.cpp:4:6: note: `template<class T> void print(T)`<br>
source.cpp:4:6: note: template argument deduction/substitution failed:
source.cpp:10:4: note: candidate expects 1 argument, 5 provided
这实际上是我第一次使用可变参数函数,我并不完全了解如何很好地使用它们。
我也不明白为什么这不起作用以及我能做些什么来帮助它。
【问题讨论】:
-
查看 Stroustup C++11 常见问题解答:stroustrup.com/C++11FAQ.html#variadic-templates
标签: c++ templates variadic-templates generic-programming function-templates