Skip to content

Commit

Permalink
Add hasUDA template
Browse files Browse the repository at this point in the history
  • Loading branch information
Hackerpilot committed Jun 2, 2015
1 parent e1a3cde commit 5855044
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions std/traits.d
Expand Up @@ -124,6 +124,7 @@
* $(LREF mangledName)
* $(LREF Select)
* $(LREF select)
* $(LREF hasUDA)
* ))
* )
* )
Expand Down Expand Up @@ -6403,3 +6404,71 @@ unittest
static assert(is(typeof(a) == real));
static assert(is(typeof(b) == real));
}

/**
* Determine if a symbol has a given $(LINK2 ../attribute.html#uda, user-defined attribute).
*/
template hasUDA(alias symbol, alias attribute)
{
import std.typetuple : staticIndexOf;
import std.traits : staticMap;

static if (is(attribute == struct) || is(attribute == class))
{
template GetTypeOrExp(alias S)
{
static if (is(typeof(S)))
alias GetTypeOrExp = typeof(S);
else
alias GetTypeOrExp = S;
}
enum bool hasUDA = staticIndexOf!(attribute, staticMap!(GetTypeOrExp,
__traits(getAttributes, symbol))) != -1;
}
else
enum bool hasUDA = staticIndexOf!(attribute, __traits(getAttributes, symbol)) != -1;
}

///
unittest
{
enum E;
struct S;
struct Named { string name; }

@("alpha") int a;
static assert(hasUDA!(a, "alpha"));
static assert(!hasUDA!(a, S));
static assert(!hasUDA!(a, E));

@(E) int b;
static assert(!hasUDA!(b, "alpha"));
static assert(!hasUDA!(b, S));
static assert(hasUDA!(b, E));

@E int c;
static assert(!hasUDA!(c, "alpha"));
static assert(!hasUDA!(c, S));
static assert(hasUDA!(c, E));

@(S, E) int d;
static assert(!hasUDA!(d, "alpha"));
static assert(hasUDA!(d, S));
static assert(hasUDA!(d, E));

@S int e;
static assert(!hasUDA!(e, "alpha"));
static assert(hasUDA!(e, S));
static assert(!hasUDA!(e, E));

@(S, E, "alpha") int f;
static assert(hasUDA!(f, "alpha"));
static assert(hasUDA!(f, S));
static assert(hasUDA!(f, E));

@(100) int g;
static assert(hasUDA!(g, 100));

@Named("abc") int h;
static assert(hasUDA!(h, Named));
}

0 comments on commit 5855044

Please sign in to comment.