Template member functions conflicting

Chris Nicholson-Sauls ibisbasenji at gmail.com
Mon Feb 19 12:59:08 PST 2007


Robin Allen wrote:
> Bruno Medeiros wrote:
>> Robin Allen wrote:
>>> class Bang(T)
>>> {
>>>     void fn(U)( Bang!(U) ot) {}
>>>         void fn(int q) {}
>>> }
>>>
>>> Why do the two member functions conflict here? One takes a class 
>>> instance and a type, the other takes an int.
>>>
>>> If this is intended, and it's not possible to overload a function 
>>> with a template function, then maybe it should be?
>>
>> They conflict, but there is an effective workaround, just turn the
>> function into a nullary template (template with zero parameters):
>>
>> import stdext.stdio;
>>
>> class Bang(T)
>> {
>>     void fn(U)(Bang!(U) ot) { writeln("U template:", typeid(U) ); }
>>     void fn() (int q) { writeln("nullary template");}
>> }
>>
>>
>> void main(char[][] args) {
>>     auto foo = new Bang!(char);
>>
>>     foo.fn(new Bang!(char));
>>     foo.fn(42);
>> }
>>
> 
> I tried this, but for me it just crashes the compiler. Probably because 
> it's actually opMul I'm defining rather than a normal function. (I'm 
> trying to make a Matrix class that you can multiply by another matrix or 
> a vector.)
> 
> The actual code is more like this:
> 
> class Matrix(int X,int Y,T)
> {
>     Matrix!(X,OY,T) opMul(OY)( Matrix!(Y,OY,T) ot );
>     Vector!(Y,T) opMul( Vector!(X,T) vec );
> }
> 
> The only way I've been able to do it is by replacing one of the operator 
> functions with a regular function. But it would be nice to do it with 
> the * sign.
> 
> 

That won't typically work as you cannot overload on return types.  If user code /only 
ever/ passed either Matrix or Vector with your opMul it might pass... but I'm dubious.  In 
this case I would recommend just defining opMul for Matrix, and providing a function for 
multiplying with a Vector.

The fact that it crashes the compiler, though, is another manner.  Try to find a small 
test case that produces it and you may have a bug report to file.

-- Chris Nicholson-Sauls


More information about the Digitalmars-d-learn mailing list