Skip to content

Instantly share code, notes, and snippets.

@JakobOvrum
Created April 1, 2015 10:22
Show Gist options
  • Save JakobOvrum/1186c66c8bfcafe474b0 to your computer and use it in GitHub Desktop.
Save JakobOvrum/1186c66c8bfcafe474b0 to your computer and use it in GitHub Desktop.
Helper templates for User-Defined Attributes
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