| |
| Posted by Don Clugston in reply to Scott Michel | PermalinkReply |
|
Don Clugston
Posted in reply to Scott Michel
| In article <ct66rn$2aso$1@digitaldaemon.com>, Scott Michel says...
>
>sergey wrote:
>> Could anybody explain how to use type (fn_t) from the following example:
>>
>> struct S {
>> int x;
>> void fn() { x++; }
>> };
>>
>> typedef void (S::*fn_t)();
>>
>> void main()
>> {
>> S a;
>> fn_t p;
>> p=NULL; // works
>> p=a.fn; // doesn't work. error expecting '('
>
>Try "&a.fn" instead. After all, you're attempting to set a pointer to point at the address of something. Otherwise, the parser is expecting a method invocation, thus, it expects a '(' to follow a.fn.
Even this isn't right. You can only write:
p = &S::fn;
You have to include the name of the class.
Note that "a" doesn't appear at all. You probably want it to call a.fn(), but
that requires a delegate, which you can't do legally in C++ (although Borland
C++, D, and C# all provide delegates).
Sergey, I didn't intend to plug my own article again, but I think you should read it...
http://www.codeproject.com/cpp/FastDelegate.asp
It was the most popular C++ article published on the CodeProject website in 2004, so you wouldn't be wasting your time. It gives a tutorial on member function pointers, and provides a library that uses some tricks to allow you to write code like:
#include "FastDelegate.h"
struct S {
int x;
void fn() { x++; }
};
typedef FastDelegate< void () > fn_t; // no parameters, returns void
void main()
{
S a;
fn_t p;
p.clear();
p.bind(&a, &S::fn); // or: p = MakeDelegate(&a, &S::fn);
p(); // calls a.fn()
}
As Scott says, you should seriously consider if you can use functors instead. But functors won't let you do run-time polymorphism, so delegates can often be very handy.
-Don.
|