Auto-add static field when inherit // mixins, templates?

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 21 13:33:46 PDT 2014


On Thursday, 21 August 2014 at 20:05:13 UTC, Ary Borenszweig
wrote:
> 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!"
> ~~~

I think such a feature would clash with a D principle: A base
class (Foo) cannot know about (or depend on) all its subclasses
(Bar), because it may be compiled separately from them.

Now, if it were only about printing the most derived class name 
(I know, it isn't), you could that in D with typeid:

import std.stdio;
class Foo
{
      void whoami()
      {
          writeln(typeid(this));
      }
}
class Bar : Foo {}
void main()
{
      Foo f = new Bar;
      f.whoami();
}


More information about the Digitalmars-d-learn mailing list