c++ – Capture variadic template arguments with lambda

Question:

You need to make a wrapper inside the template method.

Tell me how to correctly pass the list of arguments to the lambda:

template <typename Func, typename... Args>
void exec(Func&& func, Args&&... args)
{
    auto worker = [this, f = std::forward<Func>(func), a = std::forward<Args>(args)...]()
    {
        try
        {
            f(a);
        }
        catch (const std::exception& e)
        {
            std::cerr << e.what();
        }

    };
    std::async(worker);
}

how to syntactically make the transfer in this line correctly:

a = std::forward<Args>(args)...

does not understand the compiler. although calling (without a wrapper) the exec method works like this:

someInstance.exec(std::forward<Func>(func), std::forward<Args>(args)...);

Answer:

This is how it works :

#include <iostream>

template <typename Func, typename... Args>
void exec(Func&& func, Args&&... args)
{
    auto worker = [f = std::forward<Func>(func), ...a = std::forward<Args>(args)]()
    {
        f(a...);
    };
    
    worker();
}

void f(int a, double b) {
    std::cout << a << " " << b << "\n";
}

int main() {
    exec(f, 42, 1.234);
}

But you need C ++ 20.

For C ++ 17, it can be wrapped in std::tuple :

template <typename Func, typename... Args>
void exec(Func&& func, Args&&... args)
{
    auto worker = [f = std::forward<Func>(func), a = std::make_tuple(std::forward<Args>(args)...)]()
    {
        std::apply(f, a);
    };
    
    worker();
}
Scroll to Top