c++ - 如何通过参数包传递引用?

标签 c++ reference c++11 variadic-templates

我有以下代码:

#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/

相关文章:

c++ - 有模板复制构造函数时不生成默认构造函数

c++ - C++ Linux 中损坏的双链表

c++ - 尝试将用户输入传递给字符串 (C++)

C++11 move 构造函数

C++ 11 Thread 与 Boost Thread 有什么区别吗?

c++ - 未为使用默认模板参数声明的别名模板指定模板参数时出错

c++ - 请给我关于 C++ 回文循环的建议

c# - 使用什么序列化程序(到 xml)进行循环引用和自定义字段?

c++ - 什么时候可以安全且轻松地将引用变量用作别名?

java - 二叉搜索树添加方法引用迷路