Call function inside a lambda passed to a thread

2019-02-20 16:12发布

I'm trying to create a object that can be given a function and its parameters to his constructor. This class will then call the given function inside a lambda that is instead passed to a thread. Something along the lines of

class worker {
public:
    template <class Fn, class... Args>
    explicit worker(Fn f, Args ... args) {
        t = std::thread([&]() -> void {
                f(args...);
        });
    }
private:
    std::thread t;
};

int main() {
    worker t([]() -> void {
        for (size_t i = 0; i < 100; i++)
            std::cout << i << std::endl;
    });

    return 0;
}

But I get the following error

error: parameter packs not expanded with '...': f(args...);

What am I doing wrong here? Any help would be appreciated.

1条回答
啃猪蹄的小仙女
2楼-- · 2019-02-20 16:28

As said in the comments, this compile fine with gcc-4.9 (and above), but if you need to use gcc-4.8 you can add parameters to the lambda in the worker constructor and pass the arguments via the std::thread constructor:

class worker {
public:
    template <class Fn, class... Args>
    explicit worker(Fn f, Args ...args) {
        t = std::thread([f](Args ...largs) -> void {
                f(largs...);
        }, std::move(args)...);
    }
private:
    std::thread t;
};

This will also create copy of the arguments in the lambda arguments, unlike the capture by reference you were using [&] that was probably incorrect in this case (see @Yakk comment).

查看更多
登录 后发表回答