vtbl jamming
Jarrett Billingsley
kb3ctd2 at yahoo.com
Mon Sep 10 07:08:50 PDT 2007
"Kirk McDonald" <kirklin.mcdonald at gmail.com> wrote in message
news:fc35na$30pq$1 at digitalmars.com...
> It sort of does. You can fake them with delegates:
>
> class Foo {
> void bar() { writefln("Foo.bar"); }
> }
>
> void ptr_call(void function() fn, Object o) {
> void delegate() dg;
> dg.ptr = o;
> dg.funcptr = fn;
> dg();
> }
>
> void main() {
> auto f = new Foo;
> void function() fn = &Foo.bar;
> ptr_call(fn, f);
> }
>
> I write this without testing it, and may have left out a cast or two. But
> the idea is sound. (Indeed, Pyd relies on it.)
Here's another way, which does it all at compile time. It also has the
advantage of doing a polymorphic call.
struct PTM(Type, char[] name)
{
const fullName = Type.stringof ~ "." ~ name;
alias ReturnTypeOf!(mixin(fullName)) Ret;
alias ParameterTupleOf!(mixin(fullName)) Params;
Ret opCall(Type obj, Params params)
{
mixin("return obj." ~ name ~ "(params);");
}
}
class A
{
void foo()
{
Stdout.formatln("Foo!");
}
int bar(int x)
{
Stdout.formatln("Bar: {}", x);
return x * 2;
}
}
void main()
{
scope a = new A();
PTM!(A, "foo") f;
PTM!(A, "bar") b;
f(a);
Stdout.formatln("Got: {}", b(a, 6));
}
It also has fairly similar semantics to C++'s pointers-to-methods: each PTM
is associated with a single class and with a single method. I'm sure you
could make it a little more flexible though, at the cost of having to
manually specify the parameter types when creating the PTM.
(Also note that the PTM struct is 1 byte.)
More information about the Digitalmars-d
mailing list