|
||||
|
Section 33:
|
[33.5] How can I avoid syntax errors when creating pointers to members?
Use a typedef. Yea, right, I know: you are different. You are smart. You can do this stuff without a typedef. Sigh. I have received many emails from people who, like you, refused to take the simple advice of this FAQ. They wasted hours and hours of their time, when 10 seconds worth of typedefs would have simplified their lives. Plus, face it, you are not writing code that only you can read; you are hopefully writing your code that others will also be able to read — when they're tired — when they have their own deadlines and their own challenges. So why intentionally make life harder on yourself and on others? Be smart: use a typedef. Here's a sample class:
class Fred {
public:
int f(char x, float y);
int g(char x, float y);
int h(char x, float y);
int i(char x, float y);
...
};
The typedef is trivial:
typedef int (Fred::*FredMemFn)(char x, float y); ← please do this!That's it! FredMemFn is the type name, and a pointer of that type points to any member of Fred that takes (char,float), such as Fred's f, g, h and i. It's then trivial to declare a member-function pointer:
int main()
{
FredMemFn p = &Fred::f;
...
}
And it's also trivial to declare functions that receive
member-function pointers:
void userCode(FredMemFn p)
{ ... }
And it's also trivial to declare functions that return member-function
pointers:
FredMemFn userCode()
{ ... }
So please, use a typedef. Either that or do not send me email
about the problems you have with your member-function pointers!
|
|||