How to write a variable number of arguments to a lambda function

I tried the following code but not compiling.

template <class T, class... A> void tpool::enqueue(T&& func, A&&... args) { std::function<void()> task([func, args] () { //... }); } 
+4
source share
2 answers

Just use ellipses. In clause 5.1.2 / 23 of the C ++ 11 standard:

A capture followed by an ellipsis is a packet extension (14.5.3). [Example:

 template<class... Args> void f(Args... args) { auto lm = [&, args...] { return g(args...); }; lm(); } 

-end example]

Note. Interestingly, GCC refuses to compile this (see live example ):

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

But, given the above example from the Standard, this is definitely a compiler problem.

+7
source

When you use args in capture, you need ellipsis:

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

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


All Articles