Function templates with more than one declaration?

Brian Palmer d at brian.codekitchen.net
Mon Apr 14 11:27:19 PDT 2008


boyd Wrote:

> Would a function template work in this case perhaps?
> 
>    Atom atom(string name)(){
>      static Atom myAtom;
>      myAtom = Atom(name);
>      return myAtom;
>    }
> 
> Cheers,
> Boyd

Thanks for the quick response, Boyd -- I probably should have explained what Atoms do, and why I wanted that static constructor in there. Depending on how the Atom is being used, your approach could case Atom(name) to be called each time, instead of once during module initialization. For example:

    void doSomething(string[atom] params) {
      doSomethingElse(params[atom!("name")]);
    }

would call Atom("name") during each call to doSomething(). For Atoms to improve performance they need to be stored after the first lookup.

Sometimes it pays to step away from the computer for a minute though -- I really just needed to use two templates where I was using one:

    Atom atom(string name)() {
      return _atom!(name).myAtom;
    }

    private template _atom(string name) {
      static Atom myAtom;
      static this() { myAtom = Atom(name); }
    }



More information about the Digitalmars-d-learn mailing list