Function name as text

Jarrett Billingsley kb3ctd2 at yahoo.com
Wed Dec 5 13:38:08 PST 2007


"Craig Black" <cblack at ara.com> wrote in message 
news:fj714p$2u7b$1 at digitalmars.com...
>I have been considering porting some C++ code to D.  One of the classes I 
>would have to port is an event queue class where each event on the queue 
>has a delegate and a text string that points to the function name that the 
>delegate refers to.  The function name is used to visualize the event queue 
>for run-time debugging purposes.  It is important to capture both the class 
>name and the function name as text.
>
> In C++ I had a macro called DISPATCH that used the stringize operator # to 
> capture the name of the function.  The good (and bad) thing about C++ in 
> this case is that when specifying a pointer to a member, you must fully 
> qualify the function name, so you would have something like this.
>
> class Foo {
> public:
>  void bar() {}
> };
>
> Foo *foo = new Foo;
> Event event = DISPATCH(foo, &Foo::bar);
>
> Using the stringize operator, the DISPATCH macro could capture the text 
> string "Foo::bar" as well as the member function pointer.  Here is the 
> equivalent code in D..
>
> Foo foo = new Foo;
> Event event = dispatch(&foo.bar);
>
> Which is much more elegant, except that I can't figure out a way to 
> capture the name of the function and it's class.  I tried fiddling with 
> the stringof operator but that doesn't seem to work.
>
> Any ideas?
>

template dispatch(char[] methodName)
{
    Event dispatch(T)(T thing)
    {
        Event ret;
        ret.name = T.stringof ~ "." ~ methodName;
        ret.func = mixin("&thing." ~ methodName);
        return ret;
    }
}

Now you can use it like:

Event event = dispatch!("bar")(foo);

It's kind of backwards-looking, but it's probably the best you can do 
without macros/static params. 





More information about the Digitalmars-d mailing list