如何通过参数包传递引用

How to pass a reference through a parameter pack?

本文关键字:引用 包传递 参数 何通过      更新时间:2023-10-16

我有以下代码:

#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;
}