简体   繁体   中英

Defining operators for specific instances of a generic

I am attempting to implement the generic Vector3 struct, and havethe operators for my struct that allows basic math when the type T is a numeric (int, float, double, long, short)

I had thought the way to do this was to just define the 4 basic operators for all each something like

public static Vector3<int> operator +(Vector3<int> left, Vector3<int> right) but that gives me the error that at least one of the parameters must be of the containing type (which is Vector3 in this case)

I feel reasonably confident there is a way for me to define a Vector3 generic, and still have the convenience of the standard operators, but I can not seem to figure out what I need to write syntactically.

I believe you are trying to do something like this:

public class Vector3<T>
{ 
    T x; T y; T z; 

    public static Vector3<int> operator + (Vector3<int> lhs, Vector3<int> rhs)
    {
        //Stuff
    }
}

This is not allowed. Why not? Well imagine you wrote a method like this:

public static void Foo<T>()
{
    var lhs = new Vector3<T>();
    var rhs = new Vector3<T>();

    var result = lhs + rhs;
}

Should the compiler allow this to compile or not? Because this would work:

Foo<int>();

But this would fail:

Foo<string>();

Because the compiler can't guarantee it'll work, it's not allowed.

If you have a burning desire to implement operator overloading for certain types of Vector3, you have to subclass it:

public class Vector3Int : Vector3<int>
{
    public static Vector3Int operator + (Vector3Int lhs, Vector3Int rhs)
    {
        //Stuff
    }
}

That would work. Note that I had to change struct to class as you can't inherit a struct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM