On Attributes

Steven Schveighoffer schveiguy at yahoo.com
Mon Nov 27 19:23:33 UTC 2017


On 11/27/17 2:10 PM, A Guy With a Question 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 have some degree of success with global application and inference.

Note that ALL attributes can be applied in one of 3 ways:

1. At the declaration:

@safe int foo();
@safe int bar();

2. In a scope:

@safe {
    int foo();
    int bar();
}

3. as a label:

@safe:
    int foo();
    int bar();

There are some limitations, such that it will NOT apply to functions 
inside classes or structs. Also, attributes without an opposite 
attribute (e.g. pure) cannot be undone once you apply at the top with a 
label.

Note that templates automatically infer attributes, you do not have to 
write them:

T foo(T)() {... } // implies @safe if possible

Functions which return auto also imply attributes:

auto foo() {... } // implies @safe if possible

The reason here is because the implementation of the function must be 
available to properly compile, therefore the compiler can infer the 
proper attributes.

Hope this helps.

-Steve


More information about the Digitalmars-d-learn mailing list