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();
}
Run Code Online (Sandbox Code Playgroud)
错误:
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>)}'
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用typedef函数指针或lambda.是不是可以使用static_cast?
jpa*_*cek 11
你必须强制转换为函数指针类型(不是函数类型)
thread t1(static_cast<void (*)()>(&hello));
^^^
Run Code Online (Sandbox Code Playgroud)
函数类型(例如void())是通过其参数和返回类型表示函数的类型.但是程序中不能有这些类型的变量(函数本身除外,这些是函数类型的左值).但是,可以引用函数或指向函数的指针,您要使用后者.
当您不尝试创建函数类型的变量(或临时对象)时(例如,您键入一个函数类型,或将其用作模板参数),它的使用就可以了.std::function<void()>只使用参数来指定其参数和返回类型,因此其设计者决定使用这种时尚的语法.在内部,它不会尝试使用该类型创建变量.
| 归档时间: |
|
| 查看次数: |
3315 次 |
| 最近记录: |