将模板args传递给std :: thread

时间:2016-02-27 08:20:56

标签: c++ c++11

我有一个小问题,将args传递给调用模板函数的std :: thread。

template <typename F, typename... A>
void start(int interval, F func, A&&... args)
{
    if (_running.load(std::memory_order_acquire)) {
        stop();
    };
    _running.store(true, std::memory_order_release);
    _thread = std::thread([this, interval, func, args]()
    {
        while (_running.load(std::memory_order_acquire))
        {
            func(std::forward<A>(args)...);

            for (int i = 0; (i <= (interval / 200)) && _running.load(std::memory_order_acquire); i++)
                std::this_thread::sleep_for(std::chrono::milliseconds(200));
        }
    });
}

编辑: 添加了一些细节 我应该能够通过任何ammount或args传递任何函数来“启动”

void ThreadProc(HWND hwnd)
{
    Beep(1000, 100);
}

start(2000, ThreadProc, hwnd);

错误:

error C3520: 'args': parameter pack must be expanded in this context
    note: see reference to function template instantiation 'void CallBack::start<void(__cdecl *)(HWND),HWND&>(int,F,HWND &)' being compiled
    1>          with
    1>          [
    1>              F=void (__cdecl *)(HWND)
    1>          ]

1 个答案:

答案 0 :(得分:0)

_thread = std::thread([this, interval, func, &args...]()