lundi 26 janvier 2015

std::thread taking lambda with ref arg fails to compile

I'm reading C++ concurrency in action. Chapter 2.4 describes a parallell_accumulate algorithm.


I tried - as a learning experiment - to replace the functor used there, with a generic lambda.


I've distilled the compilation error down to:



#include <thread>

template <typename T>
struct f {
void operator() (T& result) { result = 1;}
};

int main() {
int x = 0;
auto g = [](auto& result) { result = 1; };

std::thread(f<int>(), std::ref(x)); // COMPILES
std::thread(g, std::ref(x)); // FAILS TO COMPILE
}


The error message:



In file included from /usr/include/c++/4.9/thread:39:0,
from foo.cpp:1:
/usr/include/c++/4.9/functional: In instantiation of ‘struct std::_Bind_simple<main()::<lambda(auto:1&)>(std::reference_wrapper<int>)>’:
/usr/include/c++/4.9/thread:140:47: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = main()::<lambda(auto:1&)>&; _Args = {std::reference_wrapper<int>}]’
foo.cpp:13:31: required from here
/usr/include/c++/4.9/functional:1665:61: error: no type named ‘type’ in ‘class std::result_of<main()::<lambda(auto:1&)>(std::reference_wrapper<int>)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/4.9/functional:1695:9: error: no type named ‘type’ in ‘class std::result_of<main()::<lambda(auto:1&)>(std::reference_wrapper<int>)>’
_M_invoke(_Index_tuple<_Indices...>)
^


My compiler version



$ g++ --version
g++ (Ubuntu 4.9.1-16ubuntu6) 4.9.1


Why do the compilation fail for the lambda but not the functor?


Aucun commentaire:

Enregistrer un commentaire