On Tuesday, 9 April 2019 at 10:53:49 UTC, Ron Tarrant wrote:
On Monday, 8 April 2019 at 14:56:46 UTC, Mike Parker wrote:

In the subsequent sections, I show both long and short (eponymous) forms of enum and function templates.

In your book, Mike, you stated:

Remember, a template is only instantiated once for each set of arguments and the same instantiation can be repeated in multiple modules throughout a program. If each instantiation were scoped locally, the template would no
longer work as expected.

That leads me to speculate that it should be possible to use a class template as a sort of singleton. But, because a class template (from what I understand currently) needs to be instantiated using 'new,' I'm thinking maybe it isn't possible.

Can you (or someone else) clear this up for me, please?

Instantiating a class template is not like instantiating a single instance of an object. What it does is create an implementation of the class, not an instance. So given this:

class Foo(T) {
   T item;
}

Then this instantiation (which, byt the way, does not need new -- an alias will do the trick):

alias IntFoo = Foo!int;

Essentially does this:

class FooWithInt {
    int item;
}

Of course, the symbol will be different than 'FooWithInt', but the point is for every T there has to be a uniquely named implementation of Foo.


What I have in mind is a template wrapped around a GTK AccelGroup that could then be instantiated in the MainWindow as well as inside any MenuItem needing a keyboard shortcut assignment.

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();





Reply via email to