2013-02-16 129 views
5

的标准::异步调用考虑下面的类:成员函数

class Foo 
{ 
    private: 
     void bar(const size_t); 
    public: 
     void foo(); 
}; 

现在Foo::foo()应该启动线程执行bar,所以这是它是如何实现的:

void Foo:foo() 
{ 
    auto handle = std::async(std::launch::async, &Foo::bar, this, 0); 
    handle.get(); 
} 

此相克完美的作品++ -4.6.3,但不能用g ++ - 4.5.2,错误信息是

include/c++/4.5.2/functional:180:9: Error: must use ».« or »->« to call pointer-to-member function in »std::declval with _Tp = void (Foo::*)(long unsigned int), typename std::add_rvalue_reference<_Tp>::type = void (Foo::&&)(long unsigned int) (...)«, e.g. »(... -> std::declval with _Tp = void (Foo::*)(long unsigned int), typename std::add_rvalue_reference<_Tp>::type = void (Foo::*&&)(long unsigned int)) (...)«

所以显然,错误在于旧版本的g ++。有可能通过使公众的方法,引入以下辅助函数来解决此问题:

void barHelp(Foo* foo, const size_t n) 
{ 
    foo->bar(n); 
} 
void Foo:foo() 
{ 
    auto handle = std::async(std::launch::async, barHelp, this, 0); 
    handle.get(); 
} 

然而,制作方法public是不是最好的设计决策。有没有另外的方法来解决这个问题没有改变编译器,并保持私有方法?

回答

9

问题似乎是,它不会与成员函数打好。也许你可以std::bind的成员函数的对象首先,它传递给std::async前:

auto func = std::bind(&Foo::bar, this, std::placeholders::_1); 
auto handle = std::async(std::launch::async, func, 0); 
+0

工作正常,谢谢! – stefan 2013-02-16 16:57:49