www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Finding Super class from Derived Class at compile time

reply LeqxLeqx <mitchelldlarson protonmail.ch> writes:
Hello!

I have a question regarding attempting to access the super class 
of a derived class at compile time.

Specifically, if I have:

     class A { }
     class B : A { }

     void func(T)()
     {
       /+ find super-class of T +/
     }

     int main ()
     {
       func!B; /+ func would find A +/
       return 0;
     }

in `func(T)()' how would I (if it is possible) check what class T 
derives from? So `func!B' would be able to find `A'? I've looked 
through the __traits options but none of them seem to be able to 
do what I need. Unfortunately (for me anyways), __traits(parent, 
...) returns the module, not the super class.

Is this at all possible (at compile time)?

Thank you
Apr 14 2019
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 04/14/2019 10:06 PM, LeqxLeqx wrote:
 Hello!
 
 I have a question regarding attempting to access the super class of a 
 derived class at compile time.
BaseClassesTuple and friends: https://dlang.org/phobos/std_traits.html Ali
Apr 14 2019
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Monday, 15 April 2019 at 05:20:37 UTC, Ali Çehreli wrote:
 BaseClassesTuple and friends:

   https://dlang.org/phobos/std_traits.html
And the implementation of that is the `is` expression https://dlang.org/spec/expression.html#IsExpression specifically, with the `super` keyword. static if (is(YourClass ListOfBaseTypes == super)) // use ListOfBaseTypes here; you can foreach, index, or slice it to get what you are looking for.
Apr 15 2019
parent LeqxLeqx <mitchelldlarson protonmail.ch> writes:
On Monday, 15 April 2019 at 22:45:59 UTC, Adam D. Ruppe wrote:
 On Monday, 15 April 2019 at 05:20:37 UTC, Ali Çehreli wrote:
 BaseClassesTuple and friends:

   https://dlang.org/phobos/std_traits.html
And the implementation of that is the `is` expression https://dlang.org/spec/expression.html#IsExpression specifically, with the `super` keyword. static if (is(YourClass ListOfBaseTypes == super)) // use ListOfBaseTypes here; you can foreach, index, or slice it to get what you are looking for.
That's perfect. Thank you both so much!
Apr 15 2019