Mpac
Mpac

Reputation: 931

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] () {
        //...
    });
}

Upvotes: 4

Views: 1382

Answers (2)

Andy Prowl
Andy Prowl

Reputation: 126432

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.

Upvotes: 7

Some programmer dude
Some programmer dude

Reputation: 409176

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...] () {
        //...
    });
}

Upvotes: 3

Related Questions