Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable number of arguments to lambda function

Tags:

c++

lambda

I am trying to pass variable number of arguments to a lambda function. what is the prototype to accept variable number of arguments in lambda functions? should i write a named function instead of lambda?

std::once_flag flag;

template<typename ...Args>
void gFunc(Args... args)
{
}

template<typename ...Args>
void func(Args... args)
{
    std::call_once(flag,[](/*accept variable number of arguments*/... args)
                        {
                                // more code here
                                gFunc( args...);
                        }, 
                        args...
                        );
}

the below signatures give error:

[&](){ }
[&args](){ }
[&args...](){ }
[&,args...](){ }
[&...args](){ }
like image 206
ProgramCpp Avatar asked Oct 24 '14 17:10

ProgramCpp


2 Answers

In C++14 you can do

auto lambda = [](auto... args) {...};

But in your case I believe simple capture is enough:

std::call_once(flag, [&] {
                         gFunc(args...); // will implicitly capture all args
                     }
               );
like image 104
Anton Savin Avatar answered Sep 28 '22 04:09

Anton Savin


Try this :

template<typename ...Args>
void func(Args... args)
{
    std::call_once(flag,[&, args...]( )
                        {   
                         gFunc( args...);
                        }, 
                        args...
                        );
}

Stolen from here

§ 5.1.2 A capture followed by an ellipsis is a pack expansion (14.5.3).

[ Example:
template<class... Args>
void f(Args... args) {
auto lm = [&, args...] { return g(args...); };
lm();
}
—end example ]
like image 43
P0W Avatar answered Sep 28 '22 05:09

P0W