Non-ugly ways to implement a 'static' class or namespace?

Steven Schveighoffer schveiguy at gmail.com
Fri Jan 20 15:00:10 UTC 2023


On 1/20/23 6:28 AM, thebluepandabear wrote:

> This type of semantics is not possible in D, which sucks.

Well, static methods do exactly this.

If you want to disable class creation, then use `@disable this();`, if 
you want to make all methods static, put `static:` at the top of the class.

Note that at this point, the class becomes a namespace. You can use a 
template as a namespace as well, though it can be a bit ugly:

```d
template Algo_ns()
{
    void drawLine(Canvas c, Pos from, Pos to) {...}
}

// need this to avoid the instantiation syntax
alias Algo = Algo_ns!();
```

The benefit here is that other things that classes do (generate 
typeinfo, add to the type system, etc.) would be wasted, so this is not 
done for a template.

-Steve


More information about the Digitalmars-d-learn mailing list