jinsediaoying
jinsediaoying
CC#
Created by jinsediaoying on 1/19/2024 in #help
Need help with generic vector math
I'm trying to create a Vector type with generic math approach.
//my vector class
public readonly struct Vec2<TScalar>(TScalar x, TScalar y) :
IVector<Vec2<TScalar>, TScalar>
where TScalar : INumber<TScalar>
{ ... }

//my interface
public interface IVector<TSelf, TScalar> : IVector<TScalar>,
IAdditiveIdentity<TSelf, TSelf>,
IMultiplicativeIdentity<TSelf, TScalar>,
IAdditionOperators<TSelf, TSelf, TSelf>,
ISubtractionOperators<TSelf, TSelf, TSelf>,
IMultiplyOperators<TSelf, TScalar, TSelf>,
IDivisionOperators<TSelf, TScalar, TSelf>,
IUnaryNegationOperators<TSelf, TSelf>,
IUnaryPlusOperators<TSelf, TSelf>,
IEqualityOperators<TSelf, TSelf, bool>,
IEquatable<TSelf>
where TSelf : IVector<TSelf, TScalar>
where TScalar : INumber<TScalar>
{
static abstract int Rank { get; }
TScalar this[int axis] { get; }

public static virtual TScalar Dot(TSelf a, TSelf b)
{
TScalar val = TScalar.Zero;
for (int i = 0; i < TSelf.Rank; i++)
{
val += a[i] * b[i];
}
return val;
}
}

//my extension method
public static TScalar Dot<TVec, TScalar>(this TVec a, TVec b)
where TVec : IVector<TVec, TScalar>
where TScalar : INumber<TScalar>
{
return TVec.Dot(a, b);
}

//my test code
Vec2<float> a = new(1, 2);
var x = a.Dot(a);//error here, said cs0411: The type arguments for method 'method' cannot be inferred from the usage
//my vector class
public readonly struct Vec2<TScalar>(TScalar x, TScalar y) :
IVector<Vec2<TScalar>, TScalar>
where TScalar : INumber<TScalar>
{ ... }

//my interface
public interface IVector<TSelf, TScalar> : IVector<TScalar>,
IAdditiveIdentity<TSelf, TSelf>,
IMultiplicativeIdentity<TSelf, TScalar>,
IAdditionOperators<TSelf, TSelf, TSelf>,
ISubtractionOperators<TSelf, TSelf, TSelf>,
IMultiplyOperators<TSelf, TScalar, TSelf>,
IDivisionOperators<TSelf, TScalar, TSelf>,
IUnaryNegationOperators<TSelf, TSelf>,
IUnaryPlusOperators<TSelf, TSelf>,
IEqualityOperators<TSelf, TSelf, bool>,
IEquatable<TSelf>
where TSelf : IVector<TSelf, TScalar>
where TScalar : INumber<TScalar>
{
static abstract int Rank { get; }
TScalar this[int axis] { get; }

public static virtual TScalar Dot(TSelf a, TSelf b)
{
TScalar val = TScalar.Zero;
for (int i = 0; i < TSelf.Rank; i++)
{
val += a[i] * b[i];
}
return val;
}
}

//my extension method
public static TScalar Dot<TVec, TScalar>(this TVec a, TVec b)
where TVec : IVector<TVec, TScalar>
where TScalar : INumber<TScalar>
{
return TVec.Dot(a, b);
}

//my test code
Vec2<float> a = new(1, 2);
var x = a.Dot(a);//error here, said cs0411: The type arguments for method 'method' cannot be inferred from the usage
So I get a error at the test code, how can I do this right?
8 replies