On 8/21/14, 6:38 AM, MarisaLovesUsAll wrote:
tl;dr - how to get child classname from inherited parent function at
compile time?
class A { string getName(); };
class B { };
B foo = new B;
assert(foo.getName() == "B");
...
Hi! I'm stuck at one issue, and I don't know how to solve it. I think
this is about mixins/templates, isn't it?
When inherit from base class Component, I need to auto-create child own
static fields with child type.
It should look like this, after compilation:
class Component
{
//it doesn't matter to have any fields here
//but it's important to be able to create an instance of Component
//and when inherit, all childs will get their own "static T list;"
where T is a type of child.
};
class Sprite:Component
{
static Sprite list; //auto-added
static void fun() { } //auto-added, operates with Sprite
}
class Camera:Component
{
static Camera list; //auto-added
static void fun() { } //auto-added, operates with Camera instead of
Sprite
}
...
//so this must be correct:
Component foo;
Sprite bar;
void foobar(Component one) { }
foobar(Sprite);
...
Sorry for bad English.
Best regards, Alex
I'll tell you how it's done in Crystal in case someone wants to come up
with a proposal to make it work in D.
~~~
class Foo
macro inherited
def method_in_{{@class_name.downcase.id}}
puts "Hello {{@class_name.id}}!"
end
end
end
class Bar < Foo
end
Bar.new.method_in_bar #=> "Hello Bar!"
~~~
When you inherit a class, the macro "inherited" is automatically
executed by the compiler in the context of the inheriting class. There
you can use special variables like "@class_name" and interpolate them
with {{ ... }}.
I guess a similar thing to do in D would be to define a function to be
executed at compile time and automatically mix it, and the context of
execution would be the inherited class.
(sorry if this is of no interest to all of you, let me know if I should
stop trying to bring ideas to D from other languages)