Introduction to traits (and __traits)

Benjamin Thaut code at benjamin-thaut.de
Fri Aug 30 12:40:46 PDT 2013


Am 30.08.2013 21:36, schrieb Joseph Rushton Wakeling:
> Hello all,
>
> I find myself wanting to write for the first time one of these
> isSomething(T) or hasSomething(T) templates that perform compile-time
> checks, so I was hoping people could give me some good general advice on
> traits.
>
> The goal here is to be able to confirm (i) type T has certain members
> and (ii) they have certain properties.  (This is for my graph library,
> Dgraph.)
>
> So, to start off with, I thought I'd try starting with,
>
>      template isGraph(G)
>      {
>          isGraph = __traits(hasMember, G, "directed") &&
> isBoolean!(typeof(G.directed));
>      }
>
> ... which I'd assumed would cover the case where G does not have a
> member "directed".  But in fact if I pass it a struct that does not have
> the entity .directed defined therein, it will return an error:  "no
> property 'directed' for type ..."
>
> So, can someone give me a good idea of how to go about writing such a
> compile-time template that checks (i) for the existence of certain
> methods/functions/members and (ii) confirms their characteristics, such
> as their return values or arguments?
>
> Thanks & best wishes,
>
>      -- Joe

You need to put it into a static if, otherwise the compiler will 
continue semantic checks on the second part of the expression. E.g.

template isGraph(G)
{
   static if(__traits(hasMember, G, "directed"))
     enum bool isGraph = isBoolean!(typeof(G.directed));
   else
     enum bool isGraph = false;
}


More information about the Digitalmars-d-learn mailing list