11

次のクラスを検討してください。

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: エラー: 使用する必要があります ». « または »-> « _Tp = void (Foo::*)(long unsigned int)、型名 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();
}

ただし、メソッドを公開することは、最適な設計上の決定ではありません。コンパイラを変更せずにメソッドをプライベートのままにすることなく、この問題を回避する別の方法はありますか?

4

2 に答える 2

13

問題は、メンバー関数でうまく機能しないことです。おそらくstd::bind、メンバー関数を最初にオブジェクトに渡してから、に渡すことができstd::asyncます。

auto func = std::bind(&Foo::bar, this, std::placeholders::_1);
auto handle = std::async(std::launch::async, func, 0);
于 2013-02-16T16:49:59.733 に答える