Remix.run Logo
p0w3n3d 5 hours ago

This are merely instanceof switches. Generics mean that you write

  fun(a,b): return a+b 
and if the a + b is doable, it will be done. You don't need to specify the list of types that accepts this syntax. The difference between this and duck typing is that you can also specify interfaces (or traits in c++) that will say that this type is quackable so

  fun(a <? implements Quackable>): a.quack()
is reusable. What is the difference between this and simple interface implementation? It took me some time to find this example in the narrowest version possible.

  class <T has trait Number> Complex(a T, b T):
    Complex<T> operator+(Complex<T> other): return new Complex(this.a + other.a, this.b+other.b)
    Complex<T> operator-(Complex<T> other): return new Complex(this.a - other.a, this.b-other.b)
    Complex<T> operator*(Complex<T> other):
       return Complex(this.a * other.a - this.b * other.b, this.a * other.b + this.b * other.a)
The generic renders this code reusable, so if only you can create a new type, let's say vector, that supports +,-, and multiply you can have complex algebra on those vectors
mikepurvis 2 hours ago | parent [-]

At least in C++ there's also the matter that the type switching happens at compile time, not runtime. You get a new instance of the function for each type that it's called with.

That's why C++ libraries with generic interfaces need to have their full implementations in the header or else have explicit instantiations for known supported types. If you compile the library first and the project later, there's no way of knowing at library-compile-time which instantiations of the generic will later be needed, and like, the types might not even exist yet at that point.