Rick de Water
Rick de Water

Reputation: 2642

How to generate constant values with generic math

I have the following generic math function:

private static T Fade<T>(T t)
    where T : IFloatingPoint<T>
{
    return t * t * t * (t * (t * 6 - 15) + 10);
}

This doesn't compile however, since 6, 15 and 10 are not of type T.

The best solution I could come up with was to define a static class like this:

private static class GenericValues<T>
    where T : IFloatingPoint<T>
{
    public static readonly T Two = T.One + T.One;
    public static readonly T Three = Two + T.One;
    public static readonly T Four = Three + T.One;
    public static readonly T Five = Four + T.One;

    public static readonly T Six = Five + T.One;
    public static readonly T Ten = Five * Two;
    public static readonly T Fifteen = Five * Three;
}

And then the function becomes this:

private static T Fade<T>(T t)
    where T : IFloatingPoint<T>
{
    return t * t * t * (t * (t * GenericValues<T>.Six - GenericValues<T>.Fifteen) + GenericValues<T>.Ten);
}

This feels a bit like a hack though, is there a nicer way to do this?

Upvotes: 8

Views: 308

Answers (1)

Guru Stron
Guru Stron

Reputation: 142008

You can use one of the INumberBase<T>.CreateX methods, for example INumberBase<TSelf>.CreateChecked<TOther>(TOther) to convert the number literals to the generic number type:

private static T Fade<T>(T t)
    where T : IFloatingPoint<T>
{
    return t * t * t * 
        (t * (t * T.CreateChecked(6) - T.CreateChecked(15)) + T.CreateChecked(10));
}

Upvotes: 10

Related Questions