User defined attributes use
simendsjo
simendsjo at gmail.com
Sun Sep 15 11:31:37 PDT 2013
On Sunday, 15 September 2013 at 17:34:06 UTC, matovitch wrote:
> Hi everyone,
>
> I read the documentation about user defined attributes, but I
> don't see their uses. Ok, it'a a template expression you can
> link to a declaration, but what are they useful for ? (not sure
> about the syntax ;-))
>
> Can you declare a template constraint as a user defined
> attribute to do something like :
>
> void
> template_function_which_go_back_and_forth(@("Bidirectional")
> @("Range") BR)(BR br) {...}
>
> This would be awesome (even if not really occidental) to do
> something like:
>
> @("SmallTypeSet") @("MediumTypeSet") @("LargeTypeSet") Type
>
> This could allow to build tree based category structure.
It enables declarative programming.
And because this is D, there is no runtime overhead.
A common use is to add semantics to types and instances that is
difficult or very intrusive to do by creating structs/classes by
hand.
A little validation example:
@nonNull // An instance shouldn't be allowed to be null
class C {
@matches("[0-9]+")
string someNumber;
@interval!"(]"(0, 10) // (0, 10] range
int someInt;
}
C c;
validate(c); // returns ["C is null", "someNumber doesn't match
'[0-9]+'", "someInt is outside the interval '(0, 10]'"]
And ORMs usually use annotations:
@table("some_tablename")
class C {
@id("id_field_name")
int id;
}
Take a look at C# and Java libraries to see how many uses
attributes/annotations - they are still quite new in D, so they
are still underutilized.
A very big difference is of course that UDAs are available at
compile time :)
More information about the Digitalmars-d-learn
mailing list