Introduction to traits (and __traits)
Joseph Rushton Wakeling
joseph.wakeling at webdrake.net
Fri Aug 30 12:36:33 PDT 2013
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
More information about the Digitalmars-d-learn
mailing list