方法指针转换时如何选择const方法重载

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

我有一个带有重载方法的类:

#include <iostream>
#include <utility>

struct Overloads {
    void foo() {
        std::cout << "foo" << std::endl;
    }

    void foo() const {
        std::cout << "const foo" << std::endl;
    }
};

我知道我可以使用指向成员函数的指针(

&Overloads::foo
)。 由于这里函数重载了,所以必须制作一个
static_cast

int main() {

    auto overloads = Overloads{};

    auto foo_func = static_cast<void (Overloads::*)()>(&Overloads::foo);

    (overloads.*foo_func)();  // foo is printed - as expected

    // No idea where to put const and why:
    // auto const_foo_func = static_cast<void (Overloads::*) ()>(&Overloads::foo);

    //(overloads.*const_foo_func)();  // const foo output is expected
}

我明白了,如何获取非常量 foo 的函子。我怎样才能得到一个 const foo 重载?

c++ c++17 pointer-to-member
1个回答
0
投票

您只需将

const
限定符添加到成员函数指针中的函数类型,就像在成员函数声明中一样:

auto foo_func = static_cast<void (Overloads::*)() const>(&Overloads::foo);
© www.soinside.com 2019 - 2024. All rights reserved.