How to use static_cast to resolve overloaded funct

2020-07-22 19:00发布

  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?

标签: c++
4条回答
\"骚年 ilove
2楼-- · 2020-07-22 19:19

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

EDIT:

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

查看更多
beautiful°
3楼-- · 2020-07-22 19:22

if you use std thread you can just write

std::thread(hello);
std::thread(hello, "blabla");
查看更多
Fickle 薄情
4楼-- · 2020-07-22 19:25

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.

查看更多
别忘想泡老子
5楼-- · 2020-07-22 19:40

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) );
查看更多
登录 后发表回答