is there any reason UFCS can't be used with 'new'?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 30 11:07:46 PDT 2014


On 09/30/2014 10:35 AM, "Nordlöw" wrote:

 > On Sunday, 28 September 2014 at 20:28:11 UTC, Jay wrote:
 >> fwiw here's what i wrote:
 >>
 >> template New(T) if (is(T == class)) {
 >>     T New(Args...) (Args args) {
 >>         return new T(args);
 >>     }
 >> }
 >
 > My try
 >
 > template New(T) if (is(T == class))
 > {
 >      T New(Args...) (Args args) {
 >          return new T(args);
 >      }
 > }
 >
 > unittest
 > {
 >      class C { int x, y; }
 >      auto x = New!C;
 > }
 >
 > fails as
 >
 > typecons_ex.d(60,16): Error: outer function context of
 > typecons_ex.__unittestL64_4 is needed to 'new' nested class
 > typecons_ex.__unittestL64_4.C
 > typecons_ex.d(67,14): Error: template instance
 > typecons_ex.New!(C).New!() error instantiating

Apparently, a class definition even inside a unittest blocks are 
considered to be nested classes.

Normally, objects of nested classes are created by the 'this.new' 
syntax, 'this' meaning the object that wraps the nested class.

class Outer
{
     class Inner
     {}

     Inner makeInner()
     {
         return this.new Inner();
     }
}

void main()
{
     Outer o = new Outer;
     Outer.Inner i = o.makeInner();
}

i contains a context pointer to its creators so that it can access the 
outer object's members.

To make a nested class unnested, declare it as static, which seems to 
work in your case as well:

     class C { int x, y; }
     auto x = New!C();

Ali



More information about the Digitalmars-d-learn mailing list