Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

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

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?

Answer*

Draft saved
Draft discarded
Cancel
3
  • Well, I see. And const after Overloads::* makes the whole type const. This part works in the same way as simple function pointers. Commented Aug 31, 2024 at 22:45
  • 1
    @ГеоргийГуминов 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. Commented Aug 31, 2024 at 22:46
  • 2
    @ГеоргийГуминов 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). Commented Aug 31, 2024 at 22:46

lang-cpp

AltStyle によって変換されたページ (->オリジナル) /