digitalmars.D.learn - .classinfo by Class name
- Adam (13/13) Dec 01 2011 Hello again!
- Adam (13/13) Dec 01 2011 Nevermind - sorry for the clutter.
- Justin Whear (11/30) Dec 01 2011 .classinfo is for getting information about an object at __runtime__.
- Adam (3/3) Dec 01 2011 Ah; I should have clarified - I didn't want an *instance* of the
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
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
.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
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