【问题标题】:std::async call of member function成员函数的 std::async 调用
【发布时间】:2013-02-01 11:40:46
【问题描述】:

考虑以下类:

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::*)(long unsigned int), typename std::add_rvalue_reference<_tp>::type = void (Foo::&&)(long unsigned int) (...)«,例如»(... -> 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();
}

但是,将方法公开并不是最好的设计决策。是否有其他方法可以解决此问题 更改编译器并将方法保留为私有?

【问题讨论】:

    标签: c++ class asynchronous c++11 function-pointers


    【解决方案1】:

    问题似乎是它不能很好地与成员函数配合使用。也许您可以先将std::bind 的成员函数传递给您的对象,然后再将其传递给std::async

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

    【讨论】:

      【解决方案2】:

      我更喜欢 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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 1970-01-01
        • 2020-09-10
        • 1970-01-01
        • 2021-02-19
        相关资源
        最近更新 更多