14

I have the following code:

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

Currently it prints 1000, that is, the new value of b gets lost somewhere. I guess that's because foo passes the parameters in the parameter pack by value. How can I fix that?

p12
  • 1,161
  • 8
  • 23

2 Answers2

19

By using reference :

template<class Fun, class... Args>
void foo(Fun f, Args&&... args)
{
    f( std::forward<Args>(args)... );
}
BЈовић
  • 62,405
  • 41
  • 173
  • 273
8

like this:

#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;
}
Nim
  • 33,299
  • 2
  • 62
  • 101