Template function : use the array's one !
John C
johnch_atms at hotmail.com
Wed Feb 18 08:14:05 PST 2009
TSalm Wrote:
> Hello,
>
> I'm searching to have a generic comparator function.
>
> I done this :
>
> /* ------------ CODE -------------------- */
> import tango.io.Stdout;
>
> /***
> * Not for arrays
> ***/
> int compare(T)(T o1,T o2)
> {
> static if ( is( T bar == class ) || is( T bar == struct ) )
> return o1.opCmp(o2);
>
> else
> return o2 - o1;
> }
>
> /***
> * For arrays
> ***/
> int compare(T:T[])(T[] o1,T[] o2)
Change this line to:
int compare(T:T[])(T o1, T o2)
> {
> size_t minLength = ( o1.length<o2.length ? o1.length : o2.length) ;
>
> for (size_t i=0;i<minLength;i++)
> {
> int result = compare(o1[i],o2[i]);
>
> if (result != 0)
> return result;
> }
>
> return o2.length - o1.length ;
>
> }
>
> /***
> * Test
> ***/
> void main()
> {
> byte[] a = [10,12,13];
> byte[] b = [15,16,17];
> Stdout( compare(a,b) ).newline ;
> }
> /* ------------ END CODE ---------------- */
>
>
>
> But this code return a compilation error :
> test_cmp.d(12): Error: cannot implicitly convert expression (o2 - o1) of
> type byte[] to int
> test_cmp.d(41): template instance test_cmp.compare!(byte[]) error
> instantiating
>
> It seems it's the first compare function (without array in parameter)
> which is hook.
>
> How can I declare this compare function to use specific code to compare
> arrays ?
> Thanks in advance,
> TSalm
More information about the Digitalmars-d-learn
mailing list