C++ std::成员函数的异步调用

C++ std::成员函数的异步调用,c++,class,asynchronous,c++11,function-pointers,C++,Class,Asynchronous,C++11,Function Pointers,考虑以下类别: 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(); } 这在g++-4

考虑以下类别:

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();
}
这在g++-4.6.3中可以完美地工作,但在g++-4.5.2中却不行,错误消息是

include/c++/4.5.2/functional:180:9:错误:必须使用»。«或»->«调用»std::declval with»Tp=void(Foo::*)(长无符号int)、typename std::add_-rvalue_-reference::type=void(Foo:&&&)(长无符号int)(…)«,例如»(…->std::declval with»Tp=void(Foo:*)(长无符号int)(长无符号int),typename std::add_rvalue_reference::type=void(Foo::*&&)(长无符号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();
}

然而,公开一个方法并不是最好的设计决策。有没有其他方法可以解决这个问题,而不必更改编译器并将方法保留为私有的?

问题似乎在于它无法很好地处理成员函数。也许您可以在将成员函数传递给
std::async
之前,先将其绑定到对象上:

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

我更喜欢lambdas而不是std::bind

#include <iostream>
#include <future>

class Foo
{
private:
    void bar(const size_t)
    {}
public:
    void foo()
    {
        auto handle = std::async(std::launch::async, [this](){
            this->bar(0);
        });
        handle.get();
    }
};

int main()
{
    Foo foo;
    foo.foo();
    return 0;
}
        auto handle = std::async(std::launch::async, [this](const size_t num){
            this->bar(num);
        }, 0);