这个例子使用了一个通用的可变参数模板和函数。我想打印出传递给 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
这实际上是我第一次使用可变参数函数,我不太了解如何用好它们。
我也不明白为什么这不起作用以及我可以做些什么来帮助它。
最佳答案
c++17更新!
由于这个问题很笼统,而且在 C++17 中你可以做得更好,所以我想给出两种方法。
解决方案-我
使用 fold expression ,这可能只是
#include <iostream>
#include <utility> // std::forward
template<typename ...Args>
constexpr void print(Args&&... args) noexcept
{
((std::cout << std::forward<Args>(args) << " "), ...);
}
int main()
{
print("foo", 10, 20.8, 'c', 4.04f);
}
输出:
foo 10 20.8 c 4.04
( See Live Online )
解决方案-II
在if constexpr
的帮助下,现在我们可以避免为递归提供基本情况/0 参数情况 variadic template function .这是因为编译器在编译时丢弃了 if constexpr
中的 false 语句。
#include <iostream>
#include <utility> // std::forward
template <typename T, typename...Ts>
constexpr void print(T&& first, Ts&&... rest) noexcept
{
if constexpr (sizeof...(Ts) == 0)
{
std::cout << first; // for only 1-arguments
}
else
{
std::cout << first << " "; // print the 1 argument
print(std::forward<Ts>(rest)...); // pass the rest further
}
}
int main()
{
print("foo", 10, 20.8, 'c', 4.04f);
}
输出
foo 10 20.8 c 4.04
( See Live Online )
关于c++ - 如何使用可变参数模板打印出函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342633/