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

标签 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.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();
}

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

最佳答案

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

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

关于c++ - std::成员函数的异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14912635/

相关文章:

android - 如何将联系人详细信息存储为类变量android

javascript - 将 asyncTest 与 for 循环一起使用

javascript - 从使用多个异步调用的函数返回

c++ - 无法读入由空格分隔的两个字符串

c++ - 调用静态方法

c++ - 在 OpenCV 中更改相机设置

c++ - 为什么我的类(class)不是原型(prototype)?

c++ - FreeType 中的新线像素距离?

c++ - 我正在从 C 迁移到 C++,但我没有创建类

java - 异步服务中的 Spring 请求范围?通过 threadLocal 变量实现 ThreadScope,加上一个 AsyncAspect 来清理