如何通过参数包传递引用? [英] How to pass a reference through a parameter pack?
本文介绍了如何通过参数包传递引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
#include <cstdio>
template<class Fun, class... Args>
void foo(Fun f, Args... args)
{
f(args...);
}
int main()
{
int a = 2;
int b = 1000;
foo([](int &b, int a){ b = a; }, b, a);
std::printf("%d\n", b);
}
当前打印1000
,即b
的新值在某处丢失.我猜这是因为 foo
按值传递参数包中的参数.我该如何解决?
Currently it prints 1000
, that is, the new value of b
gets lost somewhere. I guess that's because foo
passes the parameters in the parameter pack by value. How can I fix that?
推荐答案
使用参考:
template<class Fun, class... Args>
void foo(Fun f, Args&&... args)
{
f( std::forward<Args>(args)... );
}
这篇关于如何通过参数包传递引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文