Knowledge points:
- In C++, functions are distinguished and identified by their names and parameters. In order to compile a function call, the compiler must first do a name lookup, which may involve argument dependency lookup for functions, and may be followed by template argument deduction for function templates.
static_cast
Can be used to disambiguate function overloading by performing a function-to-pointer conversion to the specified type
The sample code is as follows
#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;
}
output indication
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
reference