www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - is expression on templated types

reply simendsjo <simen.endsjo pandavre.com> writes:
I have a templated struct, and I'd like to check if a given type is this 
struct. I have no idea how I should write the is expression..

struct S(int C, int R, T) {
     T[C][R] data;
}
template isS(T) {
     enum isS = is(T : S); // How can I see if T is a kind of S no 
matter what values S is parameterized on?
}
unittest {
     static assert(isS!(S!(1,1,float)));
     static assert(!isS!(float[1][1]));
}
Jun 25 2011
parent reply "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
On Sat, 25 Jun 2011 15:57:03 +0200, simendsjo <simen.endsjo pandavre.com>  
wrote:

 I have a templated struct, and I'd like to check if a given type is this  
 struct. I have no idea how I should write the is expression..

 struct S(int C, int R, T) {
      T[C][R] data;
 }
 template isS(T) {
      enum isS = is(T : S); // How can I see if T is a kind of S no  
 matter what values S is parameterized on?
 }
 unittest {
      static assert(isS!(S!(1,1,float)));
      static assert(!isS!(float[1][1]));
 }
template isS(T) { static if ( is( T t == S!(C,R,U), int C, int R, U ) ) { enum isS = true; } else { enum isS = false; } } This works, but I thought the following had been added. Apparently not: template isS(T) { static if ( is( T t == S!U, U... ) ) { enum isS = true; } else { enum isS = false; } } As for the weird way to write this, it is caused by some variants of the isExpression not being available outside static if. -- Simen
Jun 25 2011
parent simendsjo <simen.endsjo pandavre.com> writes:
On 25.06.2011 16:32, Simen Kjaeraas wrote:
 On Sat, 25 Jun 2011 15:57:03 +0200, simendsjo
 <simen.endsjo pandavre.com> wrote:

 I have a templated struct, and I'd like to check if a given type is
 this struct. I have no idea how I should write the is expression..

 struct S(int C, int R, T) {
 T[C][R] data;
 }
 template isS(T) {
 enum isS = is(T : S); // How can I see if T is a kind of S no matter
 what values S is parameterized on?
 }
 unittest {
 static assert(isS!(S!(1,1,float)));
 static assert(!isS!(float[1][1]));
 }
template isS(T) { static if ( is( T t == S!(C,R,U), int C, int R, U ) ) { enum isS = true; } else { enum isS = false; } } This works, but I thought the following had been added. Apparently not: template isS(T) { static if ( is( T t == S!U, U... ) ) { enum isS = true; } else { enum isS = false; } } As for the weird way to write this, it is caused by some variants of the isExpression not being available outside static if.
Thanks - works like a charm. The is expression is quite a complex beast though. Has anyone written any articles on it, or some more examples than the documentation? Think I need many examples before I grok it.
Jun 25 2011