加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 成员函数的std :: async调用

发布时间:2020-12-16 03:21:08 所属栏目:百科 来源:网络整理
导读:考虑以下课程: 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();} 这
考虑以下课程:
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: 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,0);
    handle.get();
}

但是,公开方法并不是最好的设计决策.有没有其他方法可以解决此问题而无需更改编译器并将方法保持为私有?

解决方法

问题似乎是它对成员函数不会很好.也许你可以先将成员函数std ::绑定到你的对象,然后再将其传递给std :: async:
auto func = std::bind(&Foo::bar,std::placeholders::_1);
auto handle = std::async(std::launch::async,func,0);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读