[33.8] How do I declare a pointer-to-member-function that points to a const member function?
Short answer: add a const to the right of the )
when you use a typedef to declare the
member-function-pointer type.
For example, suppose you want a pointer-to-member-function that points at
Fred::f, Fred::g or Fred::h:
class Fred {
public:
int f(int i) const;
int g(int i) const;
int h(int j) const;
...
};
Then
when you use a typedef to declare
the member-function-pointer type, it should look like this:
// FredMemFn points to a const member-function of Fred that takes (int)
typedef int (Fred::*FredMemFn)(int) const;
^^^^^—this is the const
That's it!
Then you can declare/pass/return member-function pointers just like normal:
void foo(FredMemFn p) ← pass a member-function pointer
{ ... }
FredMemFn bar() ← return a member-function pointer
{ ... }
void baz()
{
FredMemFn p = &Fred::f; ← declare a member-function pointer
FredMemFn a[10]; ← declare an array of member-function pointers
...
}