问题
Compiling with
$ g++ -std=c++0x -I "inc" src/*.cpp
and receiving
src/ProcessGroup.cpp:25:10: error: no matching constructor for initialization of 'std::__1::thread'
thread t(&Process::Run, p, exit_code);
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:349:9: note: candidate template
ignored: couldn't infer template argument '_Fp'
thread::thread(_Fp&& __f, _Args&&... __args)
^
g++
is complaining that it cannot find a matching constructor for the arguments I give it:
void
ProcessGroup::Add(Process *p)
{
Process::status_t *exit_code = new Process::status_t;
thread t(&Process::Run, p, exit_code);
instance_t *instance = new instance_t(&p, &t);
threads.insert(pair<instance_t*, Process::status_t*> (instance, exit_code));
}
// FIXME: Should *not* be using system(); this was just a standup to
// test multithreading
Process::status_t
Process::Run() const
{
return system(command.c_str());
}
void
Process::Run(Process::status_t &exit_code)
{
exit_code = Run();
}
As far as I can tell, I am asking the compiler for the constructor which matches
thread( <some function>, <some object>, <some argument>... )
which should work according to this answer to Start thread with member function. It doesn't, so obviously something must be wrong, but what is it?
The entire code is available on GitHub. I apologize to people looking at this post in the future—the history of that repository will likely be rewritten.
回答1:
You want:
std::thread t(static_cast<void(Process::*)(Process::status_t&)>(&Process::Run),
p, std::ref(*exit_code));
Since your member function is overloaded, you need to specify the desired overload explicitly. Note also the reference: objects of std::thread
own all their bound state, so reference semantics to outside state have to be made explicit. And you need to dereference the pointer exit_code
, of course.
来源:https://stackoverflow.com/questions/26179175/multithreading-with-overloaded-member-functions