Thread overview | ||||||
---|---|---|---|---|---|---|
|
December 01, 2011 .classinfo by Class name | ||||
---|---|---|---|---|
| ||||
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. |
December 01, 2011 Re: .classinfo by Class name | ||||
---|---|---|---|---|
| ||||
Posted in reply to Adam | 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 } |
December 01, 2011 Re: .classinfo by Class name | ||||
---|---|---|---|---|
| ||||
Posted in reply to Adam | .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
> }
|
December 01, 2011 Re: .classinfo by Class name | ||||
---|---|---|---|---|
| ||||
Posted in reply to Justin Whear | 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. |
Copyright © 1999-2021 by the D Language Foundation