In c 20 we can use concepts
which works like the where
keyword in c# but I'm wondering how can i check T
has some operator overloaded on it.
c Example:-
template <class T>
concept SupportPlusEqual = requires (T t) { t = t };
template <class T>
requires SupportPlusEqual <T>
void Add (T& lhs, T& rhs)
{
lhs = rhs;
}
In this code T
must have =
operator defined.
Is there any way to do the same in
c#
?
CodePudding user response:
I think the closest equivalent is if you use .NET 7, interfaces can now specify operators with the new static abstract and virtual members feature. For example:
public interface IHasAdd<T> where T : IHasAdd<T>
{
static abstract T operator (T a, T b);
}
To use it, make a type like this:
public class Foo : IHasAdd<Foo>
{
public Foo(int someValue)
{
SomeValue = someValue;
}
public int SomeValue { get; init; }
public static Foo operator (Foo a, Foo b)
{
return new Foo(a.SomeValue b.SomeValue);
}
}
An example method that can use the interface:
public T AddTogether<T>(T first, T second)
where T : IHasAdd<T>
{
return first second;
}
Which means you can now do this:
var result = AddTogether(new Foo(1), new Foo(2));
//result.SomeValue == 3
CodePudding user response:
You can only restrict generic types to interfaces, there is no way to require a specific operator to be implemented.
From .Net 7 there is the generic math feature that accomplishes something similar. This includes a bunch of interfaces, like IAdditionOperators<TSelf,TOther,TResult>, that can be used as a generic type restriction, and should also have associated operators defined to perform the corresponding operator.
Note that c templates and c# generic while superficially similar are implemented quite differently. While c resolves everything in compile time, c# includes the generic types in the CIL code, and is only converted to machine code when jitted.