Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture variable number of arguments in lambda function

I tried the following code but doesn't compile.

template <class T, class... A>
void tpool::enqueue(T&& func, A&&... args) {
    std::function<void()> task([func, args] () {
        //...
    });
}
like image 747
Mpac Avatar asked Dec 27 '22 04:12

Mpac


2 Answers

Just use the ellipses. Per paragraph 5.1.2/23 of the C++11 Standard:

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 ]

Note: Interestingly enough, GCC is refusing to compile this (see the live example):

template <class T, class... A>
void foo(T&& func, A&&... args) {
    std::function<void()> task([func, args...] () {
        //...
    });
}

But considering the above example from the Standard, this is definitely a compiler issue.

like image 151
Andy Prowl Avatar answered Jan 04 '23 22:01

Andy Prowl


When you use args in the capture, you need ellipsis:

template <class T, class... A>
void tpool::enqueue(T&& func, A&&... args) {
    std::function<void()> task([func, args...] () {
        //...
    });
}
like image 23
Some programmer dude Avatar answered Jan 04 '23 22:01

Some programmer dude