知识点:
- c++中通过名称和参数来区分和识别函数。为了编译函数调用,编译器必须首先进行名字查找,对于函数可能涉及实参依赖查找,而对于函数模板可能后随模板实参推导。
static_cast
能用来通过进行到指定类型的函数到指针转换来消解函数重载的歧义
示例代码如下
#include<iostream>
#include<thread>
using namespace std;
class Print{
public:
void print() { cout << "void print()" << 0 << endl; }
void print(int i) { cout << "void print(int i)" << i << endl; }
int print(float i) { cout << "void print(float i)" << i << endl; return 0; }
void print(int i, float j) { cout << "void print(int i, float j)" << i << " " << j << endl; }
void print(const int& i) { cout << "void print(const int& i)" << i << endl; }
};
int main() {
Print p1, p2;
thread t1(static_cast<void(Print::*)()>(&Print::print), &p1);
thread t2(static_cast<void(Print::*)(int)>(&Print::print), &p1, 1);
thread t3(static_cast<int(Print::*)(float)>(&Print::print), &p1, 2.0);
thread t4(static_cast<void(Print::*)(int, float)>(&Print::print), &p1, 3, 4.0);
thread t5(static_cast<void(Print::*)(const int&)>(&Print::print), &p2, 5); // 不能去掉&,否则调用的是void print(int i)
t1.join();t2.join();t3.join();t4.join();t5.join();
return 0;
}
输出示意
void print(int i)void print(float i)1void print()
void print(int i, float j)3 0
2
4
void print(int i)5
Process finished with exit code 0
参考