How to create friends of a class at compile time?

jfondren julian.fondren at gmail.com
Thu Jul 15 17:30:05 UTC 2021


On Thursday, 15 July 2021 at 17:21:45 UTC, Tejas wrote:
> I can do it like this in C++:
> ```
> template<class abc>
> class def
> {
>     friend typename abc;
> }
> ```
>
> I am just hopelessly confused on how to achieve the same in D.

Uncharitably: D is a friendless language. Charitably: D is so 
much more friendly that instead of a short explicit list of 
friends, D has a large implicit list of friends: everything else 
in a module.

That's why this works:

```d
class Secret {
     private int id;
}

void main() {
     import std.stdio : writeln;

     auto s = new Secret;
     writeln("visible to me: ", s.id);
}
```

But this doesn't:

```d
void main() {
     import std.stdio : writeln;
     import secret : Secret;

     auto s = new Secret;
     writeln("visible to me: ", s.id);
}
```

Error: no property `id` for type `secret.Secret`


More information about the Digitalmars-d-learn mailing list