获取const方法的地址

问题描述 投票:0回答:1

我希望能够形成一个只知道类本身和方法名称的成员指针类型。不幸的是,我无法在我的类中拥有 const 和非常量方法变体。

示例代码片段:

struct A
{
    void method() {}
    void method() const {}
};

int main()
{
    decltype(&A::method) _;
}

我也尝试过以下方法,但也没有取得多大成功:

decltype(&(std::declval<const A>().method)) _;

两种方法都失败了,因为

decltype
由于不明确而无法解决此问题:

'decltype cannot resolve address of overloaded function'

我怎样才能通过其他方式实现这一目标?

c++ function-pointers pointer-to-member decltype function-qualifier
1个回答
8
投票

你可以这样做:

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);
}

如果你想使用

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);
}

Coliru 直播

© www.soinside.com 2019 - 2024. All rights reserved.