Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a reference through a parameter pack?

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?

like image 632
p12 Avatar asked Feb 01 '12 20:02

p12


1 Answers

By using reference :

template<class Fun, class... Args>
void foo(Fun f, Args&&... args)
{
    f( std::forward<Args>(args)... );
}
like image 166
BЈовић Avatar answered Oct 27 '22 12:10

BЈовић