Is a template like copy-paste?

Sean Kelly sean at f4.ca
Fri Oct 27 07:01:49 PDT 2006


Ary Manzana wrote:
> I have a template for singleton:
> 
> ---
> template Singleton() {
> 
>    private static typeof(this) _instance;
>    private this() { }
> 
>    public static typeof(this) instance() {
>        if (!_instance) {
>            _instance = new typeof(this)();
>        }
>        return _instance;
>    }
> 
> }
> ---
> 
> I use it like this:
> 
> ---
> class Bla { // Line 15
> 
>    mixin Singleton!();
> 
> }
> 
> void main() {
>     Bla bla = Bla.instance;
> }
> ---
> 
> The compiler says:
> main.d(15): class main.Bla main.Bla.Singleton!().this is private
> 
> Then I copy-paste the template into the class definition, to see what 
> happens:
> 
> ---
> class Bla {
> 
>    private static typeof(this) _instance;
>    private this() { }
> 
>    public static typeof(this) instance() {
>        if (!_instance) {
>            _instance = new typeof(this)();
>        }
>        return _instance;
>    }
> 
> }
> 
> void main() {
>     Bla bla = Bla.instance;
> }
> ---
> 
> Compiles fine.
> 
> If I change "private this() { }" to "protected this() { }" in the 
> singleton template, both compile fine. However, this is just a 
> workaround, the first should also work.

Templates are like a form of structured macro expansion, but you're 
dealing with mixins, not templates per se.  mixins work just like 
import, so you can consider Singleton to be like its own little module 
being imported into the scope of Bla.  privates in Singleton, then, are 
not visible to Bla.


Sean



More information about the Digitalmars-d-bugs mailing list