成员函数的Decltype

Sil*_*nic 11 c++ function member decltype

class A {
    int f(int x, int j) { return 2;}
    decltype(f)* p;
};
Run Code Online (Sandbox Code Playgroud)

给我错误:

error: decltype cannot resolve address of overloaded function
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么这个错误甚至可以说是重载函数.同样地,我想也许我需要使用范围运算符来访问该函数:

class A {
    int f(int x, int j) { return 2;}
    decltype(A::f)* p;
};
Run Code Online (Sandbox Code Playgroud)

这仍然给我一个错误,但更清楚的描述:

error: invalid use of non-static member function 'int A::f(int, int)'
Run Code Online (Sandbox Code Playgroud)

为什么我不允许使用decltype来查找成员函数的类型?或者设置成员函数以static在任何一种情况下删除错误.

Sho*_*hoe 9

你真正想要的是:

struct a {
    int f(int x, int j) { return 2;}
    decltype(&a::f) p;
};
Run Code Online (Sandbox Code Playgroud)

Live demo

因为f你指的是一个成员函数.推导出的类型是:

int(a::*)(int, int)
Run Code Online (Sandbox Code Playgroud)

如果没有&编译器,则假设您正在尝试调用该函数而不向其提供参数.也许Clang的错误信息更清楚:

error: call to non-static member function without an object argument
    decltype(a::f) p;
Run Code Online (Sandbox Code Playgroud)

如果你真的不想要的指针类型,你可以在以后应用std::remove_pointer_t<type_traits>.