www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - opCall and template functions

reply Steve Teale <steve.teale britseyeview.com> writes:
Is this error intentional

import std.stdio;

class A
{
   int a;
   double b = 22.4;
   string s = "whatever";

   string opCall() { return s; }
   //T opCall(T = string)() { return cast(T) s; }

   T opCall(T)(T* dummy)
   {
      if (is(typeof(dummy) : int*))
         return cast(T) a;
      else
         return cast(T) b;
   }
}

double* D;
int* I;

void main()
{
   A a = new A();
   double d = a(D);
   writefln("d = %f", d);

   int n = a(I);
   writefln("n = %d", n);

   writefln(a());
}

strange.d(10): Error: template strange.A.opCall(T) conflicts with function
strange.A.opCall at strange.d(8)

You can make it work with the template version of opCall with no args
May 21 2009
parent reply Jarrett Billingsley <jarrett.billingsley gmail.com> writes:
On Thu, May 21, 2009 at 10:01 AM, Steve Teale
<steve.teale britseyeview.com> wrote:
 Is this error intentional

 import std.stdio;

 class A
 {
 =A0 int a;
 =A0 double b =3D 22.4;
 =A0 string s =3D "whatever";

 =A0 string opCall() { return s; }
 =A0 //T opCall(T =3D string)() { return cast(T) s; }

 =A0 T opCall(T)(T* dummy)
 =A0 {
 =A0 =A0 =A0if (is(typeof(dummy) : int*))
 =A0 =A0 =A0 =A0 return cast(T) a;
 =A0 =A0 =A0else
 =A0 =A0 =A0 =A0 return cast(T) b;
 =A0 }
 }

 double* D;
 int* I;

 void main()
 {
 =A0 A a =3D new A();
 =A0 double d =3D a(D);
 =A0 writefln("d =3D %f", d);

 =A0 int n =3D a(I);
 =A0 writefln("n =3D %d", n);

 =A0 writefln(a());
 }

 strange.d(10): Error: template strange.A.opCall(T) conflicts with functio=

 You can make it work with the template version of opCall with no args

I doubt it's intentional, but that's always been the workaround. One of the things Walter said he wanted to do for D2 was to make it possible to overload templated and normal functions like this, but that sadly hasn't materialized yet.
May 21 2009
parent Steve Teale <steve.teale britseyeview.com> writes:
Jarrett Billingsley Wrote:

 On Thu, May 21, 2009 at 10:01 AM, Steve Teale
 <steve.teale britseyeview.com> wrote:
 Is this error intentional
 strange.d(10): Error: template strange.A.opCall(T) conflicts with function
strange.A.opCall at strange.d(8)

 You can make it work with the template version of opCall with no args

I doubt it's intentional, but that's always been the workaround. One of the things Walter said he wanted to do for D2 was to make it possible to overload templated and normal functions like this, but that sadly hasn't materialized yet.

Jarrett, I can see just intuitively that it could be one of those difficult things to do, so I'll continue with the workaround, and live in hope. But I do appreciate the intention. Steve
May 22 2009