is expression for template structs/classes instances?

spir denis.spir at gmail.com
Tue Dec 21 00:09:12 PST 2010


On Tue, 21 Dec 2010 09:53:49 +0530
d coder <dlang.coder at gmail.com> wrote:

> Greetings
> 
> I want to find if a given struct type is instantiated from a
> particular template struct type. For example:
> 
> struct S (T)  {
>   alias T Type;
>   T t;
> }
> 
> And later I want to find out if a given type is of type S(*)
> (basically any type instantiated from template struct S). In fact I do
> not know the type value T used at the time of instantiating S!(T).
> 
> I was looking at "is ( Type Identifier : TypeSpecialization ,
> TemplateParameterList )" expression at
> http://www.digitalmars.com/d/2.0/expression.html#IsExpression .
> Thought there would be some way using that, but I could not find any.

I would use a flag on S, eg:

struct S(T) {
    static bool isAnS = true;
    T t;
    this (T t) {this.t = t;}
}
void main () {
    auto i = S!(int)(3);
    if (i.isAnS)
        writeln("i is an S");
}

If you were dealing with classes, you could use an interface (or fake super-class):

interface I {}
class C(T) : I {
    T t;
    this (T t) {this.t = t;}
}
void main () {
    auto i = new C!(int)(3);
    if (cast(I)i)
        writeln("i is a C");
}

[Note: In my opinion, that's precisely what interfaces are for.]
Both solutions have the nice advantage of letting down hairy is() expressions ;-)

Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d-learn mailing list