fla*_*rrr 3 c++ member-function-pointers function-pointers decltype
我希望能够形成一个只知道类本身和方法名称的成员指针类型。不幸的是,我无法在我的类中使用 const 和非常量方法变体。
示例代码片段:
struct A
{
void method() {}
void method() const {}
};
int main()
{
decltype(&A::method) _;
}
Run Code Online (Sandbox Code Playgroud)
我也尝试了以下方法,但也没有取得多大成功:
decltype(&(std::declval<const A>().method)) _;
Run Code Online (Sandbox Code Playgroud)
decltype由于歧义,这两种方法都失败了,因为无法解决这个问题:
'decltype cannot resolve address of overloaded function'
我怎样才能以其他方式实现这一目标?
你可以这样做:
struct A
{
void method() {
cout << "Non const\n";
}
void method() const {
cout << "const function\n";
}
};
int main()
{
typedef void (A::*method_const)() const;
method_const a = &A::method; //address of const method
typedef void (A::*method_nonconst)();
method_nonconst b = &A::method; //address of non const method
A var;
std::invoke(a, var);
std::invoke(b, var);
}
Run Code Online (Sandbox Code Playgroud)
如果要使用decltype()来实现相同的功能,首先必须手动选择要使用的功能static_cast<>:
int main()
{
//const
decltype( static_cast <void (A::*)() const> (&A::method) ) a;
//non const
decltype( static_cast <void (A::*)()> (&A::method) ) b;
a = &A::method;
b = &A::method;
A var;
std::invoke(a, var);
std::invoke(b, var);
}
Run Code Online (Sandbox Code Playgroud)