www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - template/non-template method name conflict

reply Michael Hewitt <dlangassist gmail.com> writes:
Hello -

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. 

Thanks,
- Mike

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

  void contains(T)(T expected, T[] array)
  {
  }
Sep 17 2007
parent reply Frits van Bommel <fvbommel REMwOVExCAPSs.nl> writes:
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.
Sep 17 2007
parent Nathan Reed <nathaniel.reed gmail.com> writes:
Frits van Bommel wrote:
 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.
Also, note that in D 2.0 overloading functions with templates will work (not implemented yet, but planned). Thanks, Nathan Reed
Sep 17 2007