Reputation: 13
Heyo everyone, I'm currently playing around with threading in C++ and stumbled upon one quirk i couldn't quite find an answer to:
in my programm is a worker class which handles creating, and talking about a thread which does X.
worker::start(string filename){
thread t(&worker::readfile,this,filename,10);
t.detach();
}
worker::readfile(string filename, int LinesToRead = -1){
stringstream ss = #open file and save as stringstream
if(LinesToRead == -1){
#read all lines from file
else{
#read "LinestoRead" lines from file
}
#does more with the stringstream to read it line by line, but not important here for the question.
}
this works fine, so does
thread t(&worker::readfile,this,filename,-1);
But why can i not call readfile as a thread with:
thread t(&worker::readfile,this, filename);
So if i leave the last variable "LinesToRead" blank it should default to -1, but i just get error messages when compiling. It's not really an issue, but I'd like to know... euhm why this is? Just calling worker::readfile(filename) works, since "LinesToRead" defaults to -1, but calling it as a thread all variables seem to be required.
Greetings
Upvotes: 1
Views: 194
Reputation: 179819
In C++, there's a difference between default parameters and overloads, even though they can achieve similar effects. For instance, you could have written this instead:
class worker {
void readfile(string filename, int LinesToRead);
void readfile(string filename) { readfile(filename, -1); }
// ...
This overload achieves the same effect: you can call it with one or two arguments, and if you call it with one it behaves as if the second argument was -1. With the overload, &worker::readfile
would be ambiguous because there are two functions named readfile
. In your default argument case, there's only one function readfile
. Therefore, &worker::readfile
is not ambiguous, but its type is void (worker::*)(string, int)
. The default argument is not part of the type.
Upvotes: 1
Reputation: 2593
The compiler will put in default arguments for you whenever the function is called. But in
thread t(&worker::readfile, this, filename);
the function call is inside the standard library. The thread
constructor gets a function pointer which can only be used with all arguments.
You could get around this using a lambda:
thread t([this, filename]() { readfile(filename); });
Upvotes: 1