UDA usage

Adam D. Ruppe destructionator at gmail.com
Fri Oct 4 20:04:19 PDT 2013


On Saturday, 5 October 2013 at 02:51:21 UTC, Matt Soucy wrote:
> * Check to see if a specific attribute exists
> * Check to see if an attribute of a specific type exists, 
> something like:

The helper functions from my web.d might help:

// checks to see if it has one of a type
// static if(hasAnnotation!(func, Foo)) { has @Foo }
// use if Foo is a simple enum.
template hasAnnotation(alias f, Attr) {
	bool helper() {
		foreach(attr; __traits(getAttributes, f))
			static if(is(attr == Attr) || is(typeof(attr) == Attr))
				return true;
		return false;

	}
	enum bool hasAnnotation = helper;
}

/// checks to see if it has an annotation with a value e.g. 
@Something(10)
template hasValueAnnotation(alias f, Attr) {
	bool helper() {
		foreach(attr; __traits(getAttributes, f))
			static if(is(typeof(attr) == Attr))
				return true;
		return false;

	}
	enum bool hasValueAnnotation = helper;
}

/// gets the thing you checked for above. so getAnnotation!(Func, 
Something) returns Something(10) (if Something is as struct)
template getAnnotation(alias f, Attr) if(hasValueAnnotation!(f, 
Attr)) {
	auto helper() {
		foreach(attr; __traits(getAttributes, f))
			static if(is(typeof(attr) == Attr))
				return attr;
		assert(0);
	}

	enum getAnnotation = helper;
}


> * Create a function that can only be called if the first 
> argument has a
> UDA of a specific type

Since the UDA is only available at compile time, you can't do 
that without some kind of template.


More information about the Digitalmars-d-learn mailing list