On Attributes

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Nov 27 19:22:37 UTC 2017


On Mon, Nov 27, 2017 at 07:10:04PM +0000, A Guy With a Question via Digitalmars-d-learn wrote:
> Hi again!
> 
> I've been trying to do my best to write idiomatically. One thing that
> is bugging me is having to mark up all of my declarations with
> attributes.  Which means I'm having to remember them all. It's a bit
> much to keep in my head with every function. Is there a good way to
> reverse this (imply the attributes by default) and then turn them off
> explicitly? Like declaring them at the top of the file so they apply
> to everything below?
[...]

You can declare attributes at the top of the file by writing "attr:"
where "attr" is pure, nothrow, @nogc, etc..

However, there is currently no way to negate these attributes afterwards.

An alternative is to let the compiler do the hard work for you by
templatizing your code. Template functions and members of templated
aggregates (structs and classes) trigger attribute inference.  You can
turn non-template functions into template functions by adding an empty
list of compile-time parameters:

	int myfunc()(int x, int y) { ... }

This has the added advantage that if myfunc is never actually referenced
elsewhere in the code, it won't even be compiled into the executable.

Of course, this is not a perfect solution, since you can't use it if for
whatever reason your function must not be a template.  One area is class
methods that must be overridden by derived classes, which can't be
template methods.  There's no way around specifying explicit attributes
in that case.


T

-- 
The fact that anyone still uses AOL shows that even the presence of options doesn't stop some people from picking the pessimal one. - Mike Ellis


More information about the Digitalmars-d-learn mailing list