Created
April 1, 2015 10:22
-
-
Save JakobOvrum/1186c66c8bfcafe474b0 to your computer and use it in GitHub Desktop.
Helper templates for User-Defined Attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private template isAttribute(Attribute) | |
{ | |
enum isAttribute(alias other) = is(typeof(other) == Attribute); | |
enum isAttribute(Other) = is(Other == Attribute); | |
} | |
private template isAttribute(alias Attribute) | |
{ | |
enum isAttribute(alias other) = is(typeof(other) == Attribute!Args, Args...); | |
enum isAttribute(Other) = is(Other == Attribute!Args, Args...); | |
} | |
template hasAttribute(alias sym, Attribute...) | |
{ | |
import std.typetuple : anySatisfy; | |
enum hasAttribute = anySatisfy!(isAttribute!(Attribute[0]), __traits(getAttributes, sym)); | |
} | |
template getAttribute(alias sym, Attribute...) | |
{ | |
import std.typetuple : Filter; | |
private alias matchingAttributes = Filter!(isAttribute!(Attribute[0]), __traits(getAttributes, sym)); | |
// Return first match | |
static if(is(matchingAttributes[0])) | |
alias getAttribute = matchingAttributes[0]; | |
else | |
enum getAttribute = matchingAttributes[0]; | |
} | |
struct Normalized {} | |
struct Type(T) | |
{ | |
alias TheType = T; | |
} | |
@Normalized @Type!float | |
void foo() {} | |
@Normalized() @Type!int() | |
void bar() {} | |
static assert(hasAttribute!(foo, Normalized)); | |
static assert(hasAttribute!(bar, Normalized)); | |
static assert(hasAttribute!(foo, Type!float)); | |
static assert(hasAttribute!(bar, Type!int)); | |
static assert(hasAttribute!(foo, Type)); | |
static assert(hasAttribute!(bar, Type)); | |
static assert(is(getAttribute!(foo, Type).TheType == float)); | |
static assert(is(getAttribute!(bar, Type).TheType == int)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment