www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - check if _argument[0] is a descendant of a specific class.

reply realhet <real_het hotmail.com> writes:
Hi, I'm googling since an hour but this is too much for me:

class A{}
class B:A{}

void foo(...){
   if(_arguments[0]==typeid(A)){
     //obviously not works for B
   }
   if(_arguments[0] ???? is_a_descendant_of A){
     //how to make it work for both A and B?
   }
}

----------------------------------

Also I tried to write a funct to compare classes by TypeInfo, but 
the TypeInfo.next field is not works in the way as I thought. It 
gives null, so the following code doesn't work.

auto isClass(C)(TypeInfo i){
   if(i==typeid(C)) return true;
   auto n = i.next;
   return n is null ? false : n.isClass!C;
}

I just wanna check if a compile_time _argument[0] is a descendant 
of a class or not.

I also tried (is : ) but without luck.

Thank you.
Jun 08 2019
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Saturday, 8 June 2019 at 21:16:14 UTC, realhet wrote:
 void foo(...){
Do you have to use the variadic thing? It is easy to do with template variadic or with just regular arrays of interfaces/base classes.
 I just wanna check if a compile_time _argument[0] is a 
 descendant of a class or not.
_arguments is a compile time construct, it is a run time thing. I kinda suspect what you really want to write is foo(T...)(T args) { } and then you can do `static if(is(arg[0] : A))` to catch both A and B. Your approach for the typeinfo thing at runtime was close though, just it isn't `next` (that's used for like immutable(A), where next is A), but `base`. http://dpldocs.info/experimental-docs/object.TypeInfo_Class.html but with the compile time list foo(T...)(T args), there's no need to do typeid/typeinfo at all.
Jun 08 2019
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Saturday, 8 June 2019 at 21:24:53 UTC, Adam D. Ruppe wrote:
 _arguments is a compile time construct, it is a run time thing.
err i meant is *NOT* a compile time construct
Jun 08 2019
parent realhet <real_het hotmail.com> writes:
On Saturday, 8 June 2019 at 21:25:41 UTC, Adam D. Ruppe wrote:
 On Saturday, 8 June 2019 at 21:24:53 UTC, Adam D. Ruppe wrote:
 _arguments is a compile time construct, it is a run time thing.
err i meant is *NOT* a compile time construct
Thank You for the fast help! At first I was happy to find the variadic example and didn't even realized, that was the runtime version. Now it works correctly with the base class check, and also it is now static and fast: static foreach(a; args){ static if(is(typeof(a)==string)){ //... }else static if(is(typeof(a) : Cell)){ if(a !is null){ //... } }else static if(is(typeof(a)==TextStyle)){ //... }else{ static assert(0, "Unsupported type: "~typeof(a).stringof); } }
Jun 08 2019