Call function inside a lambda passed to a thread

馋奶兔 提交于 2019-12-04 02:15:37

问题


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:


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).



来源:https://stackoverflow.com/questions/38614061/call-function-inside-a-lambda-passed-to-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!