如何使用static_cast来解决重载函数?

时间:2013-01-11 14:10:47

标签: c++

  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();
  }

错误:

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>)}'

我知道我可以使用typedef函数指针或lambda。 是不是可以使用static_cast

4 个答案:

答案 0 :(得分:11)

必须转换为函数指针类型(不是函数类型)

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

函数类型(例如void())是一种通过其参数和返回类型表示函数的类型。但是程序中不能有这些类型的变量(函数本身除外,这些是函数类型的左值)。但是,可以引用函数或指向函数的指针,您希望使用后者。

尝试创建函数类型的变量(或临时对象)时(例如,您键入一个函数类型,或将其用作模板参数),其使用就可以了。 std::function<void()>仅使用参数来指定其参数和返回类型,因此其设计者决定使用这种时尚的语法。在内部,它不会尝试使用该类型创建变量。

答案 1 :(得分:1)

标准确定在获取重载函数的地址时,可以使用该地址来消除歧义。这包括赋值给适当类型的变量或者转换。

您可能缺少的是&hello的类型不是函数签名,而是函数指针,因此强制转换应该是void (*)()和/或void (*)(std::string)。< / p>

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) );

答案 2 :(得分:0)

如果你使用std线程,你可以写

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

答案 3 :(得分:-1)

为什么演员? 您可以使用std :: bind或直接发送指针

编辑:

正确,这不可能完成,绝对需要演员。

相关问题