Templates - What's Up with the template keyword?
Ron Tarrant
rontarrant at gmail.com
Tue Apr 9 20:31:11 UTC 2019
On Tuesday, 9 April 2019 at 14:25:18 UTC, Mike Parker wrote:
> Off the top of my head, to get a Singleton template, you could
> implement all of your singleton plumbing (thread safety if you
> need it, etc) in the template and add a `static _instance`
> member just as you would for any non-templated singleton:
>
> class Singleton(T) {
> private static Singleton!T _instance;
> static Singleton!T instance() {
> if(_instance is null) {
> _instance = new Singleton!T;
> }
> ...
> }
>
> private T _thing;
> ...
> }
>
> And you can then instantiate directly or, more conveniently,
> use an alias:
>
> alias Accelerators = Singleton!AccelGroup;
>
> Then:
>
> Accelerators.instance.doSomething();
So, I guess the short answer is 'no.' A template can't really
substitute for a singleton without actually becoming a singleton
in and of itself.
I'm still struggling to understand templates, but I'll keep at it.
Thanks, Mike.
More information about the Digitalmars-d-learn
mailing list