1

我正在尝试创建一个对象,该对象可以将函数及其参数提供给他的构造函数。然后这个类将在一个 lambda 中调用给定的函数,该函数被传递给一个线程。类似的东西

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

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

4

1 回答 1

2

正如评论中所说,这可以使用 gcc-4.9(及更高版本)编译,但如果您需要使用 gcc-4.8,您可以在worker构造函数中向 lambda 添加参数并通过构造函数传递参数std::thread

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 评论)。

于 2016-07-27T13:30:03.560 回答