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?
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.