C++(23):为类成员函数增加this参数
C++23允许指定类成员函数的第一个参数的this类型,从而更加便于函数重载:
#include <iostream>
using namespace std;
class A{
public:
void func(this A&)
{
cout<<"in func1"<<endl;
}
void func(this const A&)
{
cout<<"in func2"<<endl;
}
void func(this A&&)
{
cout<<"in func3"<<endl;
}
};
int main()
{
A a1;
const A a2;
a1.func();
a2.func();
A().func();
return 0;
}
运行程序输出:
in func1
in func2
in func3
可以看到通过这种方式可以更方便的基于this对象的类型对函数进行重载