Resolving conflicting functions

Kirk McDonald kirklin.mcdonald at gmail.com
Mon Dec 3 18:16:34 PST 2007


Bill Baxter wrote:
> BCS wrote:
> 
>> Reply to Derek,
>>
>>> I have a Currency data type,based on a struct.
>>>
>>> I want to divide a Currency value by a scalar to return a Currency and
>>> I want to divide a Currency value by another Currency value to return
>>> a scalar. This below is my attempt but fails to compile. How does one
>>> do this?
>>>
>>> // ------------------------
>>> real opDiv(Currency pFactor)
>>> // ------------------------
>>> {
>>> return mData / pFactor.mData;
>>> }
>>> // ------------------------
>>> Currency opDiv(T)(T pFactor)
>>> // ------------------------
>>> {
>>> Currency temp;
>>> temp = this.mData / pFactor;
>>>
>>> return temp;
>>> }
>>> I get the message ...
>>>
>>> template Currency.opDiv(T) conflicts with function Currency.opDiv
>>>
>>
>> you can't have a template and non-template by the same name
>>
>> here is the nasty solution, ther might be a better one, but this 
>> should work.
>>
>> // ------------------------
>> Ret!(T) opDiv(T)(T pFactor)
>> // ------------------------
>> {
>>  Ret!(T) temp;
>>  static if(is(T == Currency))
>>    temp =  mData / pFactor.mData;
>>  else
>>    temp = this.mData / pFactor;
>>
>>  return temp;
>> }
> 
> 
> Turning the plain opDiv into a template with a different number of 
> arguments might work too:
> 
> 
> // ------------------------
> real opDiv(T=void,S=void)(Currency pFactor)
> // ------------------------
> {
>   return mData / pFactor.mData;
> }
> // ------------------------
> Currency opDiv(T)(T pFactor)
> // ------------------------
> {
>   Currency temp;
>   temp = this.mData / pFactor;
>   return temp;
> }
> 
> I say might because I'm not really sure when that trick works and when 
> it doesn't.  I posted a question about it a while back but it seems no 
> one else knows exactly how it works either.  (Or, more likely, they just 
> found the question too boring. ;-)
> 
> --bb

What about a template with /no/ arguments?

real opDiv()(Currentcy pFactor) {
     return mData / pFactor.mData;
}

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list