Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference in generic methods should fall back to lowest common ancestor #1253

Closed
cshaa opened this issue Jan 13, 2018 · 1 comment
Closed

Comments

@cshaa
Copy link

cshaa commented Jan 13, 2018

Input code:

class A {}
class B : A {}
class C : A {}

Type CommonType<T>(T x, T y) where T : A
   => typeof(T);

A a;
B b;
C c;

CommonType(a, a); // returns A
CommonType(a, b); // returns A
CommonType(b, b); // returns B

CommonType(b, c); // error 🤔

Expected result:

Falls back to the “lowest common ancestor” type and returns type of A.

Actual result:

Could not determine types of x and y, use explicit types.

Example usage

Class A could for example represent the natural numbers, B could be powers of two and C could be powers of three. Then you would implement a method Multiply such that a product of two powers of two would also be a power of two, a product of two powers of three would be another power of three and all other combinations would return a natural number – neither a power of two, nor a power of three.

If inferencing worked as I expected, you could simply write:

T Multiply<T>(T x, T y) where T : A, new()
{
    var result = new T();
    result.Value = x.Value * y.Value;
    return result;
}

Conclusion

This behavior is not limited to multiplying powers of two and three, it can be found in many other parts of mathematics (for example k-grades of a multivector are sets closed under addition). And I believe it has uses in many other fields other than maths. I believe this issue should be addressed as a part of #98.

@Joe4evr
Copy link
Contributor

Joe4evr commented Jan 13, 2018

Duplicate of #450.

@gafter gafter closed this as completed Jan 13, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants