我有以下代码:
#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
按值传递参数包中的参数。我该如何解决?
最佳答案
通过引用:
template<class Fun, class... Args>
void foo(Fun f, Args&&... args)
{
f( std::forward<Args>(args)... );
}
关于c++ - 如何通过参数包传递引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9103076/