concept name(s): container of different types which can be used like a type
https://softwareengineering.stackexchange.com/questions/356650
-
19-01-2021 - |
Вопрос
I am looking for the name(s) of a concept I heard of. I know that it does not exist in many programming languages, but I think it exists at least in C++.
Let me try to explain the concept.
Assume I want to define a generic collection in some programming language, and I want this collection to contain elements of type A
and type B
. In object oriented languages like C# or Java I can do this in at least two different ways:
- Define the collection to contain elements of type
object
. - Create a type (or interface)
C
and change the code so thatA
andB
both inherit from (or implement)C
. Then define the collection to contain elements of typeC
.
Both ways have their problems:
- allows me to put everything into the collection instead of just
A
andB
, which might not be what I want. - only works if I can modify the code of A and B.
And the concept that I am looking for allows a third approach:
- define a "type container"
T
which contains bothA
andB
and can be used like a regular type, so that I can create a collection ofT
.
In this case, I would only be able to put A
and B
into the collection, but I would not be required to change the code of A
and B
.
The same concept allows defining methods that take either an A
or B
as input and process them the same way. E.g. we might want to define a method Square
which takes an int
or a float
x
and returns x*x
. With this concept, we would not need to define two methods (one for int
, one for float
).
Решение
The name of the concept you're looking for is a Union Type.
Contrast this with an intersection type, which is where all elements of your collection would have to inherit from both A and B.