错误C2893:无法使用CTPL专门化功能模板

时间:2017-01-12 19:33:42

标签: c++ templates

我正在尝试使用CTPL进行线程池化。作为测试,我试图让它在类中使用线程函数。使用下面的代码,我收到此错误:

error C2672: 'ctpl::thread_pool::push': no matching overloaded function found
error C2893: Failed to specialize function template 'std::future<unknown-type> ctpl::thread_pool::push(F &&)'
note: With the following template arguments:
note: 'F=void (__thiscall TestClass::* )(int)'

以下是代码:

class TestClass
{
public:
    void testWorker(int id)
    {
        // do something
    }
};

int main(int argc, char **argv)
{
    ctpl::thread_pool p(2);    
    p.push(&TestClass::testWorker);
    p.stop(true);
    return 0;
}

这是被引用的CTPL的一部分:

template<typename F>
auto push(F && f) ->std::future<decltype(f(0))> {
    auto pck = std::make_shared<std::packaged_task<decltype(f(0))(int)>>(std::forward<F>(f));
    auto _f = new std::function<void(int id)>([pck](int id) {
        (*pck)(id);
    });
    this->q.push(_f);
    std::unique_lock<std::mutex> lock(this->mutex);
    this->cv.notify_one();
    return pck->get_future();
}

我很喜欢模板而且我很确定这是什么让我感到害怕。任何和所有帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

这与模板无关(除了糟糕的错误信息)。 &TestClass::testWorker是一个指向成员的函数。如果你有:

const auto tw = &TestClass::testWorker

您只能调用以下函数:

TestClass tc;
tc.*tw(0);
// or
TestClass* ptc = &tc;
ptc->tw(0);

如果您希望能够在没有类实例的情况下调用该函数来调用它,那么您需要使testWorker静态:

class TestClass
{
public:
    static void testWorker(int id)
    {
        // do something
    }
};
相关问题