Home:ALL Converter>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

Ask Time:2021-09-22T05:34:40         Author:Steve Emmerson

Json Formatter

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?

Author:Steve Emmerson,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69275801/cant-pass-lambda-that-calls-member-function-as-c11-thread-ctor-argument
yy