I'm new to std::thread
and C++11 in general. Trying to toy with the examples from https://en.cppreference.com/w/cpp/thread/thread/thread, I am trying to see if I can spawn a std::thread
using a class member function call operator with non-empty argument list as in the code below:
// main.cpp
#include <iostream>
#include <iostream>
#include <thread>
class Foo {
public:
void operator()( int& i ) {
std::cout << i << std::endl;
}
};
int main( int argc, char* argv[] ) {
Foo f;
int i = 42;
std::thread t1( f, i );
t1.join();
return 0;
}
The error message is cryptic:
$ g++ --version && g++ ./main.cpp -lpthread && ./a.out
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
In file included from /usr/include/c++/6/thread:39:0,
from ./main.cpp:5:
/usr/include/c++/6/functional: In instantiation of ‘struct std::_Bind_simple<Foo(int)>’:
/usr/include/c++/6/thread:138:26: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = Foo&; _Args = {int&}]’
./main.cpp:19:24: required from here
/usr/include/c++/6/functional:1365:61: error: no type named ‘type’ in ‘class std::result_of<Foo(int)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^~~~~~~~~~~
/usr/include/c++/6/functional:1386:9: error: no type named ‘type’ in ‘class std::result_of<Foo(int)>’
_M_invoke(_Index_tuple<_Indices...>)
In contrast, a empty argument list call operator works fine:
// main.cpp
#include <iostream>
#include <iostream>
#include <thread>
class Foo {
public:
void operator()() {
std::cout << 42 << std::endl;
}
};
int main( int argc, char* argv[] ) {
Foo f;
int i = 42;
std::thread t1( f );
t1.join();
return 0;
}
$ g++ --version && g++ ./main.cpp -lpthread && ./a.out
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
42
Is my first attempt at all feasible - do I just have a syntax error? Is there a way to spawn a std::thread using an object and its non-empty argument list call operator?
Aucun commentaire:
Enregistrer un commentaire