C++'s this() equivalent?

CM celestialmachinist at proton.me
Fri Jun 16 01:45:35 UTC 2023


On Friday, 16 June 2023 at 01:18:25 UTC, zjh wrote:
> On Friday, 16 June 2023 at 01:00:05 UTC, Steven Schveighoffer 
> wrote:
>> B b = B.make(); // call factory function
>>
>> -Steve
>
>
> Thank you for your tip.
> If could simplify it a bit more, it would be even better. It's 
> really uncomfortable without `this()`.

One could define a static opCall in his aggregate. It's still a 
factory function, but one might prefer the syntax a bit more.

```d
immutable defaultName = "John";

struct Man {
   static auto opCall() {
     typeof(this) this_;
     this_.name = defaultName;
     return this_;
   }

   string name;
}

auto m = Man();
assert(m.name == defaultName);
```

Do note that one cannot simultaneously have a constructor and a 
static opCall, even if their parameters differ.


More information about the Digitalmars-d-learn mailing list