Home > OS >  Can't pass lambda that calls member function as C 11 thread ctor argument
Can't pass lambda that calls member function as C 11 thread ctor argument

Time:09-23

I would like to pass a lambda that calls a member function as an argument to the thread constructor but have been unable to. Here's a simple example:

#include <thread>

class Foo {
    void run(void func()) {
        func();
    }

    void bar() {
        return;
    }

    void bof() {
        std::thread thread(&Foo::run, this, [&]{bar();}); // This fails to compile
    }
};

The above results in the following error:

$ g   --std=c  11 -c funcThreadArg.cpp 
In file included from /usr/include/c  /4.8.2/thread:39:0,
                 from funcThreadArg.cpp:1:
/usr/include/c  /4.8.2/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (Foo::*)(void (*)())>(Foo*, Foo::bof()::__lambda0)>’:
/usr/include/c  /4.8.2/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Foo::*)(void (*)()); _Args = {Foo* const, Foo::bof()::__lambda0}]’
funcThreadArg.cpp:14:62:   required from here
/usr/include/c  /4.8.2/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (Foo::*)(void (*)())>(Foo*, Foo::bof()::__lambda0)>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c  /4.8.2/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (Foo::*)(void (*)())>(Foo*, Foo::bof()::__lambda0)>’
         _M_invoke(_Index_tuple<_Indices...>)
         ^

Is what I want to do possible? If so, how?

CodePudding user response:

Use a std::function in Foo::run()

class Foo {
    void run(std::function<void()> func) {
        func();
    }

    void bar() {
        return;
    }

    void bof() {
        std::thread thread(&Foo::run, this, [this](){ bar(); });
        thread.join();
    }
};
  • Related