Overloading + on points
Simen kjaeraas
simen.kjaras at gmail.com
Tue Aug 31 12:22:16 PDT 2010
Eduardo Cavazos <wayo.cavazos at gmail.com> wrote:
> Hello,
>
> 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? :-)
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 )
) {...}
--
Simen
More information about the Digitalmars-d-learn
mailing list