How to pass a link through a parameter package?

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

It is currently printing 1000 , meaning the new value of b is lost somewhere. I assume that since foo passes parameters in a parameter package by value. How can i fix this?

+6
source share
2 answers

Using the link:

 template<class Fun, class... Args> void foo(Fun f, Args&&... args) { f( std::forward<Args>(args)... ); } 
+5
source

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; } 
+7
source

Source: https://habr.com/ru/post/907434/


All Articles