Function attribute best practices
Paul Backus
snarwin at gmail.com
Tue Sep 13 17:08:48 UTC 2022
On Tuesday, 13 September 2022 at 14:16:39 UTC, Ali Çehreli wrote:
> On 9/12/22 09:39, Paul Backus wrote:
>
> > Yes. Except for `@trusted`, explicit attributes on template
> code are a
> > smell.
>
> Except for 'const' as well because some templates are member
> functions. And 'const' on a member function cannot be left to
> inference because it happens to be a part of the type of the
> function, which can be overloaded.
Yes, good point. In my head, I think of attributes that apply to
the `this` parameter like `const`, `inout`, `shared`, and so as
being in a separate category from attributes that apply to the
function itself, like `@safe` and `@trusted`.
> Somebody needs to create a two dimensional table that shows
> what it means for each function attribute on a regular
> function, member function, and templates of those, and
> hopefully come up with some guidelines.
Here's my attempt, covering all the attributes found under
[`MemberFunctionAttribute`][1] in the language spec:
|Attribute|Affects |Inferred?|
|---------|--------|---------|
|nothrow |Function|Yes |
|pure |Function|Yes |
|@nogc |Function|Yes |
|@safe |Function|Yes |
|@system |Function|Yes |
|@trusted |Function|No |
|@property|Function|No |
|@disable |Function|No |
|const |this |No |
|immutable|this |No |
|inout |this |No |
|shared |this |No |
|return |this |Yes |
|scope |this |Yes |
In general, attributes with a 'Yes' in the 'Inferred?' column
should not be applied explicitly to functions that are subject to
[attribute inference][2]. This includes functions defined inside
templates, as well as nested functions and functions with an
inferred return type (i.e., `auto` functions).
[1]: https://dlang.org/spec/function.html#MemberFunctionAttributes
[2]:
https://dlang.org/spec/function.html#function-attribute-inference
More information about the Digitalmars-d-learn
mailing list