www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Module level operator overloading

Could we have module level operator overloading?

Perhaps something like this:

a op b

Gets rewritten and tried as

opfunc( a, b )

I actually tried to do this, but the compiler just complained that the 
in expression could only be used on an associative array.

This, combined with support for implicit function template instatiation, 
would allow for some cool stuff.  Stuff like a way to write array 
operations without any compiler magic, and maybe put them in phobos or 
ares.  That is good because people could then implement all sorts of 
screaming SIMD optimizations and whatnot for said array operations 
without having to know a thing about compiler writing, and the 
implementations would work on all spec-compliant D compilers.
For instance, an opAdd might look like this (sorry no optimizations):

template opAdd(T)
     T[] opAdd( T[] array1, T[] array2 )
         if ( array1.length != array2.length )
             throw new Error( "opAdd: array lengths do not match!" );

         T[] result = new T[array1.length];

         for ( uint i = 0; i < array1.length; i++ )
             result[i] = array1[i] + array2[i];

         return result;

I started to play with the idea because a friend of mine who is into 
pascal (delphi/free pascal) was telling me about how much he used the 
"in" operator.  So I figured I'd try and replicate the pascal meaning of 
"in" using some operator overloading and templating.

template opIn(T)
     bool opIn( T element, T[] array )
         for ( uint i = 0; i < array.length; i++ )
             if ( array[i] is element )
                 return true;

         return false;

void main()
     static int[4] testArray = [0,1,2,3];

     assert( 1 in testArray ); // opIn( 1, testArray )
     assert( !(5 in testArray) ); // !opIn( 5, testArray )
     // bonus points if I can write 5 !in testArray

Operator overloads being limited to OOP stopped me though.
Jul 01 2006