Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ 20 concepts alternative in c#

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any way to do the same in c#?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading