D style - member functions

Jacob Shtokolov jacob.100205 at gmail.com
Wed Apr 26 19:20:50 UTC 2023


On Wednesday, 26 April 2023 at 18:24:08 UTC, DLearner wrote:
> Consider:
> ```
> struct S1 {
>    int A;
>    int B;
>    int foo() {
>       return(A+B);
>    }
> }
>
> struct S2 {
>    int A;
>    int B;
> }
> int fnAddS2(S2 X) {
>    return (X.A + X.B);
> }

There are scenarios that won't let you use the second form, e.g. 
putting your struct under the `with()` statement:

```d
with (S1) {
     auto sum = foo(); // Works correctly
}

with (S2) {
     auto sum = foo(); // Error: function foo(S s) is not callable 
using argument types ()
}
```

In this case, the first option will be better. But there are no 
real "best practices" defined AFAIK.

However, the second form let you generalize the pattern by using 
template declaration:

```d
int fnAdd(T)(T v) {
     return (v.A + v.B); // Doesn't matter what type is this if it 
has both members A and B
}

s1.fnAdd();
s2.fnAdd();
```


More information about the Digitalmars-d-learn mailing list