template/non-template method name conflict

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Mon Sep 17 11:48:24 PDT 2007


Michael Hewitt wrote:
> I'm learning D and a friend pointed me at this newsgroup.  Please let me know if this is not an appropriate place for these sorts of questions.  My question is whether it is possible to have both templated and nontemplated methods with the same name in the same class.  A specific example of two methods that trigger a conflict is below.  Clearly in this case, an instance of the template has no chance of ever conflicting with the non-templated method signature. 

This is the 'group for it, but I'm pretty sure this particular issue has 
been answered multiple times already. For future reference, reading old 
posts may be quicker than posting a new one and waiting for an answer :).

>   void contains(char[] expected, char[] actualText)
>   {
>   }
> 
>   void contains(T)(T expected, T[] array)
>   {
>   }

No, that doesn't work because the first declares a function and the 
other declares a template (that happens to contain a function). You 
can't overload functions and templates. There's a workaround though, you 
can turn the function into a template:
---
   // Note the extra parentheses here
   void contains()(char[] expected, char[] actualText)
   {
   }

   void contains(T)(T expected, T[] array)
   {
   }
---
This turns the function into a 0-template-arg template function, 
allowing overloading. If you need multiple normal functions, you'll 
start needing another workaround; you'll probably need to specify 
"dummy" template parameters with default values (e.g. "contains(T=void, 
U=void)()") to get it to compile...

Another drawback of this workaround is that turning a member function 
into a template function disables overloading since you can't overload 
templates.


More information about the Digitalmars-d-learn mailing list