如何通过参数包传递引用
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("%dn", b);
}
当前它打印1000
,也就是说,b
的新值在某个地方丢失了。我想这是因为foo
按值传递参数包中的参数。我该怎么解决?
通过使用引用:
template<class Fun, class... Args>
void foo(Fun f, Args&&... args)
{
f( std::forward<Args>(args)... );
}
如下:
#include <iostream>
#include <functional>
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; }, std::ref(b), a);
std::cout << b << std::endl;
}
相关文章:
- 如何将指针变量作为引用参数传递?
- 通过键入的引用问题传递函数
- 移动类的成员作为常量引用参数传递
- 通过引用函数传递指针参数是什么意思?
- 将函数应用于元组中的每个元素,将每个元素强制转换为类型包中的不同类型,然后作为参数包传递
- 将非左值作为常量引用参数传递.临时是在本地作用域还是在调用方作用域中创建的?
- C++ 通过引用函数传递数组,但内容保持不变
- 关于模板化函数上传递的右值引用和传递的参数的歧义
- 我无法通过引用捕获传递 lambda
- 我可以更改将引用参数传递到指针中并使其正常工作的函数的输入(C、C++)吗?
- 当将参数包传递给另一个可变参数模板函数时,我是否必须使用 std::forward
- 将引用变量传递给函数
- Unity3D 导入 C++ DLL 用于按引用方法传递
- C++ 11 您可以通过不同线程中的引用安全地传递和访问 std::atomics 吗?
- 在一个简单的程序中奇怪的通过引用问题传递
- 在由引用对象传递中访问由引用对象传递的变量
- C++通过引用 WCHAR** 传递到函数中
- 左值引用在传递标识函数后变得无效
- 通过引用/地址传递SDL窗口
- 如何通过参数包传递引用