17

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](){ }
0

2 Answers 2

12

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
                     }
               );
Sign up to request clarification or add additional context in comments.

2 Comments

@ProgramCpp works witgcc 4.9 and clang 3.5
how would you access the arguments inside your auto lambda = [][auto... args) { ... };
6

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 ]

3 Comments

If the argument pack is expanded, how can we access the argument pack again? This signature does not work.
@ProgramCpp It works with clang and gcc 4.9
Thank you :) I would like to pass only args by value [args...](){gFunc(args...);};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.