3 ms·
So this is a bit of a tangent, but Julia has this ability to use their typing system in such a way that lets you restrict what subtypes are allowed to be assign
by vanderZwan 9y ago
So this is a bit of a tangent, but Julia has this ability to use their typing system in such a way that lets you restrict what subtypes are allowed to be assigned to a variable (I'm just using Julia as an example because that is where I first saw this, I'm sure it originated from Scala or something; I'm not a CompSci historian). So if we have these abstract types:
abstract type Number end
abstract type Real <: Number end
abstract type AbstractFloat <: Real end
abstract type Integer <: Real end
abstract type Signed <: Integer end
abstract type Unsigned <: Integer end
... then I can make a function that takes any value as long as it's a subtype of Number, which implies I can do addition and subtraction and all the other things all numbers can do. So I still have the type safety of not ending up with an object where I want a number, but it is still extremely easy to write generics in Julia[0].
Can you do something like that in C++? So like:
auto <: SomeBaseClass
Meaning auto would work just like it normally does, except that if you assign something that is not derived from SomeBaseClass the compiler complains, giving you some extra safety checks when composing code with auto all over the place.
[0] https://docs.julialang.org/en/stable/manual/types/ https://docs.julialang.org/en/stable/manual/types/
- mattnewport 9y agoConcepts give you something like this for template parameters, so instead of saying template<typename T> you can say template<Numeric T> where this would constrain the template to only be instantiable with type satisfying the Numeric concept. There's also some syntactic sugar where you can just say auto f(Numeric x) and this means template<Numeric T> auto f(T x). Concepts are in the process of standardization and are expected to be part of C++20. This is nothing to do with inheritance though in C++. Concepts are type constraints and don't require any particular inheritance hierarchy which is a much better way to handle things than using inheritance for this purpose.
- vanderZwan 9y agoThanks for the explanation! I vaguely remember reading about concepts and didn't quite get how they would be used in practice, but this seems like a good example.
- davidcuddeback 9y agoIf you're curious, that feature is called bounded polymorphism [1]. It's supported by Java and Rust, too, and I'm sure other languages as well. As mattnewport said, something similar is in the works for C++. [1] http://wiki.c2.com/?BoundedPolymorphism http://wiki.c2.com/?BoundedPolymorphism
- vanderZwan 9y agoThanks, now I know what to search for next time :)