简体   繁体   中英

How to use static_cast to resolve overloaded functions?

  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)

thread t1(static_cast<void (*)()>(&hello));
                           ^^^

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 to void (*)() and/or void (*)(std::string) .

void (*f)() = &hello;                  // target variable determines
                                       // the correct overload
thread thr( (void(*)())&hello );       // or a cast (C or static_cast<>)
thread thr( static_cast<void(*)()>(&hello) );

if you use std thread you can just write

std::thread(hello);
std::thread(hello, "blabla");

Why cast? You can use std::bind or send the pointers directly

EDIT:

Correct, this can NOT be done, a cast is definitely needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM