如何使用可变参数模板输出函数的参数? [英] How do I print out the arguments of a function using a variadic template?

查看:192
本文介绍了如何使用可变参数模板输出函数的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此示例使用通用的可变参数模板和功能。我想打印出传递给 f 的参数:

This example uses a common variadic template and function. I want to print out the arguments passed to 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

这实际上是我第一次使用可变参数函数,我不太了解如何很好地使用它们。

This is actually my first time using variadic functions and I do not exactly understand how to use them well.

我还不知道为什么它不起作用以及我可以做些什么来帮助它。

I also do not get why this isn't working and what I can do to help it.

推荐答案

您去了。您的代码中有几个错误,您可以在以下几行之间看到注释:

There you go. You had several mistakes in your code, you can see the comments between the lines below:

#include <iostream>

template <typename T>
void print(T t) {
   std::cout << t << std::endl;
}

// Base case, no args
void f() {}

// Split the parameter pack.
// We want the first argument, so we can print it.
// And the rest so we can forward it to the next call to f
template <typename T, typename...Ts>
void f(T &&first, Ts&&... rest) {
    // print it
    print(std::forward<T>(first));
    // Forward the rest.
    f(std::forward<Ts>(rest)...);
}

int main() {
    f(2, 1, 4, 3, 5);
}

请注意,在此处使用右值引用是没有意义的。您不会将参数存储在任何地方,因此只需通过const引用传递参数即可。这样,您还可以避免使用 std :: forward 来保持(无用)完美的转发。

Note that using rvalue refs here makes no sense. You're not storing the parameters anywhere, so simply passing them by const reference should do it. That way you'd also avoid using std::forward just to keep the (useless) perfect forwarding.

因此,您可以按以下方式重写 f

Therefore, you could rewrite f as follows:

template <typename T, typename...Ts>
void f(const T &first, const Ts&... rest) {
    print(first);
    f(rest...);
}

这篇关于如何使用可变参数模板输出函数的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆