调用函数里面的lambda传递给一个线程 [英] Call function inside a lambda passed to a thread

查看:682
本文介绍了调用函数里面的lambda传递给一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个对象,可以给他的构造函数及其参数。这个类将调用lambda中的给定函数,而不是传递给线程。

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;
}

但我收到以下错误

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

我在这里做错了什么?任何帮助将不胜感激。

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

推荐答案

正如在注释中所说,这编译精细与gcc-4.9如果你需要使用gcc-4.8,你可以在 worker 构造函数中向lambda添加参数,并通过 std :: thread 构造函数:

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;
};

这也将创建lambda参数中的参数的副本,与您使用的引用的捕获不同 [&] 在这种情况下可能不正确(见@Yakk评论)。

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

这篇关于调用函数里面的lambda传递给一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆