On Wednesday, 8 October 2014 at 10:36:33 UTC, andre wrote:
Hi,

could you check whether it is correct, that second line in main
failes with a compiler error?
I think the compiler should be able to deduce the type without
explicitly passing it to the method call.

Kind regards
André

template ClassTemplate()
{
  static auto deserialize(this MyType)()
  {
    return new MyType();
  }
}

class A
{
  mixin ClassTemplate;
}

void main()
{
  A a = A.deserialize!A(); // Working
  A b = A.deserialize(); // Not working
}

source\app.d(17): Error: template app.A.ClassTemplate!().deserialize cannot dedu
ce function from argument types !()(), candidates are:
source\app.d(3): app.A.ClassTemplate!().deserialize(this MyType)()

As far as I can tell, 'this' parameters don't work with static
methods. You can use typeof(this) instead:

----
template ClassTemplate()
{
   static auto deserialize()
   {
     return new typeof(this)();
   }
}

class A
{
   mixin ClassTemplate;
}

void main()
{
   A b = A.deserialize();
}
----

Be aware of the difference between template 'this' parameters and
typeof(this). A 'this' parameter is set to the (static) type of
the object, while typeof(this) is always the type of the
surrounding class.

----
class A
{
   import std.stdio;
   void printTypeofThis() {writeln(typeof(this).stringof);}
   void printThisParameter(this T)() {writeln(T.stringof);}
}

class B : A {}

void main()
{
   auto b = new B;
   b.printTypeofThis(); /* "A", because the method is in A */
b.printThisParameter(); /* "B", because b is a B (statically) */
   A a = b;
   a.printThisParameter(); /* "A", because a is an A (statically)
*/
}
----

Reply via email to