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?
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);