void hello()
{
cout << "helloworld" << endl;
}
void hello(string s)
{
cout << "hello " << s << endl;
}
void doWork()
{
thread t1(static_cast<void ()>(&hello));
thread t2(static_cast<void (string)>(&hello),"bala");
t1.join();
t2.join();
}
Error:
thread.cc|19 col 42| error: invalid static_cast from type '<unresolved overloaded function type>' to type 'void()'
thread.cc|20 col 48| error: invalid static_cast from type '<unresolved overloaded function type>' to type 'void(std::string) {aka void(std::basic_string<char>)}'
I know I can use typedef
of function pointers or a lambda.
Isn't it possible to using static_cast
?
Why cast? You can use std::bind or send the pointers directly
EDIT:
Correct, this can NOT be done, a cast is definitely needed.
if you use std thread you can just write
You must cast to function pointer types (not function types)
A function type (eg.
void()
) is a type that denotes a function by its parameters and return types. However there can be no variables of these types in the program (except function themselves, these are lvalues of function types). However, there can be references to functions or pointers to functions, of which you want to use the latter.When you don't try to make variables (or temporary objects) of function type (eg. you typedef a function type, or use it as a template parameter), its use is OK.
std::function<void()>
only uses the parameter to specify its parameters and return type, so its designers decided to use this sleek syntax. Internally, it doesn't try to make variables with that type.The standard determines that when taking the address of an overloaded function the use of that address can be used to disambiguate. That includes both assignment to a variable of the appropriate type or a cast.
What you are probably missing is that the type of
&hello
is not a function signature, but a function pointer, so the casts should be tovoid (*)()
and/orvoid (*)(std::string)
.