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
Георгий Гуминов
5051 gold badge6 silver badges19 bronze badges
1 Answer 1
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
user17732522
78.2k3 gold badges84 silver badges148 bronze badges
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.Ted Lyngmo
@ГеоргийГуминов 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.user17732522
@ГеоргийГуминов 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).lang-cpp