Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant you require operator overloading in generics [closed]

In C++, you can write code like this:

template<class T>
T Add(T lhs, T rhs)
{
    return lhs + rhs;
}

But, you can't do something like this in C#:

public static T Add<T>(T x, T y) where T : operator+
{
    return x + y;
}

Is there any reason why? I know it could be accomplished through reflection (generic Add with objects and then run type checking over it all), but that's inefficient and doesn't scale well. So, again, why?

like image 617
Cole Tobin Avatar asked Jan 15 '13 18:01

Cole Tobin


2 Answers

There is no inherent reason this could not exist. The way generic type constrains are implemented is through interface calls. If there were an interface that provided an operator+ this would work.

This interface would be required for all relevant types, though, to be as general as the C++ template-based analog.

Another issue would be that .NET has no multiple dispatch. The interface call would be asymmetric: a.Plus(b) could mean something different than b.Plus(a). Equals has the same problem, btw.

So this issue probably did not meet the "usefulness"-bar or the "cost/utility"-bar. This is not an issue of impossibility, but of practical concerns.

Proof that it is possible: ((dynamic)a) + ((dynamic)b).

like image 100
usr Avatar answered Sep 28 '22 07:09

usr


The CLR doesn't natively support such constraints, and the C# design team evidently decided to support the same set of constraints as the CLR. Presumably both the CLR team and the C# team felt that the benefits of implementing such a feature didn't outweigh the costs of speccing, implementing, and testing it.

If you want to use a .NET language that does support such constraints, consider taking a look at F#.

like image 38
kvb Avatar answered Sep 28 '22 09:09

kvb