0

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?

asked Aug 31, 2024 at 22:30
0

1 Answer 1

5

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);
answered Aug 31, 2024 at 22:34
Sign up to request clarification or add additional context in comments.

3 Comments

Well, I see. And const after Overloads::* makes the whole type const. This part works in the same way as simple function pointers.
@ГеоргийГуминов You can also typedef the signatures that becomes messy in declarations or expressions. That's what I do at least to make a complicated cast readable.
@ГеоргийГуминов Yes, the C++ declarator/type syntax might be a bit confusing initially, but it actually turns out to be quite regular. const applies to the thing left of it, except when it appears left-most of the type-id or declaration (where it is not part of the declarator, but a decl-specifier), so const after * always applies to the pointer type and const after the parameter list's ) always applies to the function type (but only non-static member function's can actually have a const-qualified function type).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.