www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - `this` as function attribute

reply Loara <loara noreply.com> writes:
In D attributes that can be associated to functions can be 
divided into two groups:

- attributes referring the function itself;
- attributes referring the implicit `this` function parameter,

so attributes like `pure`, ` safe`, `ref`, ... belong to the 
first group and `const`, `shared`, `scope` to the second one.

Maybe in the future would be necessary to apply the same 
attribute to the member function or the `this` attribute (or 
both) that forces you to reserve an additional attribute name in 
order to distinguish them.

Another approach is to use the `this` keyword in order to specify 
that the passed attributes refers to the implicit `this` 
parameter instead of the function member:

```d
class MyClass{
...
void myfun()  A  B this(  A  C ) {
...
}
...
}
```
In this example function `myfun` has the attributes ` A`, ` B` 
whereas the `this` parameter has only ` A`, ` C` attributes.

In order to avoid backward incompatibility the `this` syntax 
won't be necessary for all the attributes that can be associated 
to function parameters but don't have sense for pure functions 
like `const`, `immutable`...
Jun 04 2022
parent Timon Gehr <timon.gehr gmx.ch> writes:
On 6/4/22 18:57, Loara wrote:
 In D attributes that can be associated to functions can be divided into 
 two groups:
 
 - attributes referring the function itself;
 - attributes referring the implicit `this` function parameter,
 
 so attributes like `pure`, ` safe`, `ref`, ... belong to the first group 
 and `const`, `shared`, `scope` to the second one.
 
 Maybe in the future would be necessary to apply the same attribute to 
 the member function or the `this` attribute (or both) that forces you to 
 reserve an additional attribute name in order to distinguish them.
 
 Another approach is to use the `this` keyword in order to specify that 
 the passed attributes refers to the implicit `this` parameter instead of 
 the function member:
 
 ```d
 class MyClass{
 ...
 void myfun()  A  B this(  A  C ) {
 ...
 }
 ...
 }
 ```
 In this example function `myfun` has the attributes ` A`, ` B` whereas 
 the `this` parameter has only ` A`, ` C` attributes.
 
 In order to avoid backward incompatibility the `this` syntax won't be 
 necessary for all the attributes that can be associated to function 
 parameters but don't have sense for pure functions like `const`, 
 `immutable`...
Just put it in the argument list: ```d void myfun( A C MyClass this, ...) A B { } ```
Jun 04 2022