Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to choose const method overload when casting of method pointer is made

I have a class with overloaded method:

#include <iostream>
#include <utility>

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

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

I know that I can work with pointers to member functions (&Overloads::foo).
Since the function is overloaded here, a static_cast must be made:

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
}

I understand, how to get a functor for non-const foo. How can I get one for const foo overload?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need to add the const-qualifier to the function type in the member function pointer type, exactly in the same position as in the member function declaration:

auto const_foo_func = static_cast<void (Overloads::*)() const>(&Overloads::foo);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading