www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Overloading + on points

(Discussion originally on digitalmars-d-learn. Moving to digitalmars-d 
list.)

Eduardo Cavazos <wayo.cavazos at gmail.com> wrote:

 Here's a short program which creates a type for points and overloads 
'+'
 to do element wise addition as well as addition to floats, however it
 produces an error:

 ----------------------------------------------------------------------
 import std.stdio ;

 struct Pt
 {
    float x , y ;

    Pt opBinary ( string op ) ( Pt a ) if ( op == "+" )
      { return Pt ( x + a.x , y + a.y ) ; }

    Pt opBinary ( string op ) ( float a ) if ( op == "+" )
      { return Pt ( x + a , y + a ) ; }
 }

 void main () { Pt ( 1.0 , 2.0 ) + Pt ( 3.0 , 4.0 ) ; }
 ----------------------------------------------------------------------

 The error:

 pt_overload_test_a.d(15): Error: template instance opBinary!("+")
 matches more than one template declaration,
 pt_overload_test_a.d(8):opBinary(string op) if (op == "+") and
 pt_overload_test_a.d(11):opBinary(string op) if (op == "+")

 So, how should I go about this? :-)
Simen kjaeraas wrote:
 That is indeed a perplexing error. It is caused by dmd not knowing
 how to overload template functions based on both normal and template
 parameters.

 As for the solution:

 Pt opBinary( string op : "+", T : Pt )( T a ) {...}
 Pt opBinary( string op : "+", T : float )( T a ) {...}

 should work. More explicitly:

 Pt opBinary( string op, T )( T a ) if ( ( op == "+" ) && is( T == Pt ) )
 {...}
 Pt opBinary( string op, T )( T a ) if ( ( op == "+" ) && is( T == float )
 ) {...}
Thanks for the help Simen! Is it a bug that D doesn't handle the orignal code? Ed
Aug 31 2010