www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - .classinfo by Class name

reply Adam <Adam Anizi.com> writes:
Hello again!

A third question on D:
 Is there an argument type I can provide for a method signature
which would require a user to provide classinfo or a class name for
a class of a particular type?

That is, suppose I have a Class called "Fruit".
Is there some constraint I can impose, either in the method
signature or via static assert, which would require that the
argument of some function is a classinfo for Fruit or a subclass of
Fruit (Apple, Orange, etc)?

classinfo seems to provide a "interfaces[]" member, but I'm unsure
if this is representative of a types whole hierarchy or if it must
be browsed.
Dec 01 2011
parent reply Adam <adam anizi.com> writes:
Nevermind - sorry for the clutter.

For those who are apparently as dense as I am, this can be roughly
accomplished via Template specialization:

class Fruit {}

class Apple : Fruit {}

class Celery {}

void mustBeFruit(T : Fruit)() {
    writeln(T.classinfo.name);
}

void main() {
    mustBeFruit!(Apple)(); // Ok
    mustBeFruit!(Celery)(); // Does not compile
}
Dec 01 2011
parent reply Justin Whear <justin economicmodeling.com> writes:
.classinfo is for getting information about an object at __runtime__.

For the example given here, you don't even need templates:

void mustBeFruit(Fruit fruit)
{
    writeln(fruit.classinfo.name);
}

Since Apple, Banana, and Orange inherit from Fruit, they __are__ Fruit and 
can be passed to mustBeFruit. Getting the classinfo will then allow you to 
determine, at runtime, which subclass they are.

Justin


Adam wrote:

 Nevermind - sorry for the clutter.
 
 For those who are apparently as dense as I am, this can be roughly
 accomplished via Template specialization:
 
 class Fruit {}
 
 class Apple : Fruit {}
 
 class Celery {}
 
 void mustBeFruit(T : Fruit)() {
     writeln(T.classinfo.name);
 }
 
 void main() {
     mustBeFruit!(Apple)(); // Ok
     mustBeFruit!(Celery)(); // Does not compile
 }
Dec 01 2011
parent Adam <Adam Anizi.com> writes:
Ah; I should have clarified - I didn't want an *instance* of the
class, just to be able to restrict the signature or use of a method to
provide class info specific to a type of class.
Dec 01 2011