Function overloading concern

Carlos Santander csantander619 at gmail.com
Thu Mar 9 13:25:10 PST 2006


Sean Kelly escribió:
> While I appreciate the simple overloading rules in D, the recent 
> template improvements have me wondering how to solve cases where fully 
> qualifying names is impossible.  Here's an example using plain old 
> functions:
> 
> Module A:
> 
>     module a;
> 
>     void swap( inout int i1, inout int i2 )
>     {
>         int t = i1; i1 = i2; i2 = t;
>     }
> 
> Module B:
> 
>     module b;
> 
>     struct S {}
> 
>     void swap( inout S s1, inout S s2 )
>     {
>         S t = s1; s1 = s2; s2 = t;
>     }
> 
> Main:
> 
>     import a;
>     import b;
> 
>     template func( T )
>     {
>         void func( inout T t1, inout T t2 )
>         {
>             swap( t1, t2 );
>         }
>     }
> 
>     void main()
>     {
>         int i = 1, j = 2;
>         func( i, j );
>     }
> 
> C:\code\d>dmd test a b
> a.d(3): function a.swap conflicts with b.swap at b.d(5)
> test.d(15): template instance test.func!(int) error instantiating
> 
> While I haven't run up against this situation yet, I can see it being an 
> obstacle for large projects.  How would I resolve something like this? 
> And I expect the overloading rules will be the same for template 
> functions as they are for normal functions?  Finally, is there a more 
> D-oriented approach that might address this without language changes?
> 
> I suppose one language change that might help would be to support the 
> externally defined method syntax for primitives, so func could be 
> rewritten as:
> 
>     template func( T )
>     {
>         void func( inout T t1, inout T t2 )
>         {
>             t1.swap( t2 );
>         }
>     }
> 
> and the specialized swap for struct S could be placed within its own 
> scope.  However, this still doesn't address all situations, and I'm not 
> entirely certain that it wouldn't introduce new overloading problems 
> where none existed before.
> 
> 
> Sean

Does this work?

     import a;
     import b;

     alias a.swap swap;
     alias b.swap swap;

     template func( T )
     {
         void func( inout T t1, inout T t2 )
         {
             swap( t1, t2 );
         }
     }

     void main()
     {
         int i = 1, j = 2;
         func( i, j );
     }

-- 
Carlos Santander Bernal



More information about the Digitalmars-d mailing list