From 58550441b70ad49a5dc4714e6e0bd72ddc944d50 Mon Sep 17 00:00:00 2001 From: Hackerpilot Date: Tue, 2 Jun 2015 12:28:02 -0700 Subject: [PATCH] Add hasUDA template --- std/traits.d | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/std/traits.d b/std/traits.d index f2faf4e56f2..5b31c828d0a 100644 --- a/std/traits.d +++ b/std/traits.d @@ -124,6 +124,7 @@ * $(LREF mangledName) * $(LREF Select) * $(LREF select) + * $(LREF hasUDA) * )) * ) * ) @@ -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)); +}