Std :: async member function call

Consider the following class:

class Foo
{
   private:
      void bar(const size_t);
   public:
      void foo();
};

Foo::foo()should now start threads executing bar, so here is how it is implemented:

void Foo:foo()
{
    auto handle = std::async(std::launch::async, &Foo::bar, this, 0);
    handle.get();
}

This works flawlessly with g ++ - 4.6.3, but not with g ++ - 4.5.2, error message

include / C ++ / 4.5.2 / functional: 180: 9: Error: should use "." or "->" to call the member-pointer function in "std :: declval with _Tp = void (Foo :: *) (long unsigned int), typename std :: add_rvalue_reference <_Tp> :: type = void (Foo :: & &) (long unsigned int) (...) ", for example" (... → 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();
}

, . ?

+8
2

, -. , std::bind - , std::async:

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

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);
0

All Articles