我有以下代码:
#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)... );
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)