|
||||
|
Section 33:
|
[33.7] How do I create and use an array of pointer-to-member-function?
Use both the typedef and the #define macro described earlier, and you're 90% done. Step 1: create a typedef:
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);
...
};
// FredMemFn points to a member of Fred that takes (char,float)
typedef int (Fred::*FredMemFn)(char x, float y);
Step 2: create a #define macro:
#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))Now your array of pointers-to-member-functions is straightforward:
FredMemFn a[] = { &Fred::f, &Fred::g, &Fred::h, &Fred::i };
And your usage of one of the member function pointers is also straightforward:
void userCode(Fred& fred, int memFnNum)
{
// Assume memFnNum is between 0 and 3 inclusive:
CALL_MEMBER_FN(fred, a[memFnNum]) ('x', 3.14);
}
Note: #define macros are evil in 4 different ways:
evil#1, evil#2,
evil#3, and
evil#4. But they're still useful
sometimes. Feel ashamed, feel guilty, but when an evil construct like a macro
improves your software, use it.
|
|||