Operator overloading in generic struct: can I create overloads for specific kinds(?) of generic?

Posted by Carson Myers on Stack Overflow See other posts from Stack Overflow or by Carson Myers
Published on 2011-01-10T03:32:25Z Indexed on 2011/01/11 21:54 UTC
Read the original article Hit count: 147

Filed under:
|
|

I'm defining physical units in C#, using generic structs, and it was going okay until I got the error:

One of the parameters of a binary operator must be the containing type

when trying to overload the mathematical operators so that they convert between different units. So, I have something like this:

public interface ScalarUnit { }
public class Duration : ScalarUnit { }

public struct Scalar<T> where T : ScalarUnit
{
    public readonly double Value;

    public Scalar(double Value)
    {
        this.Value = Value;
    }

    public static implicit operator double(Scalar<T> Value)
    {
        return Value.Value;
    }
}

public interface VectorUnit { }
public class Displacement : VectorUnit { }
public class Velocity : VectorUnit { }

public struct Vector<T> where T : VectorUnit
{
    #...

    public static Vector<Velocity> operator /(Vector<Displacement> v1, Scalar<Duration> v2)
    {
        return new Vector<Velocity>(v1.Magnitude / v2, v1.Direction);
    }
}

There aren't any errors for the + and - operators, where I'm just working on a Vector<T>, but when I substitute a unit for T, suddenly it doesn't like it. Is there a way to make this work?

I figured it would work, since Displacement implements the VectorUnit interface, and I have where T : VectorUnit in the struct header. Am I at least on the right track here? I'm new to C# so I have difficulty understanding what's going on sometimes.

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics