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
- Create a type (or interface)
Cand change the code so that
Bboth inherit from (or implement)
C. Then define the collection to contain elements of type
Both ways have their problems:
- allows me to put everything into the collection instead of just
B, 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"
Twhich contains both
Band can be used like a regular type, so that I can create a collection of
In this case, I would only be able to put
B into the collection, but I would not be required to change the code of
The same concept allows defining methods that take either an
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
x and returns
x*x. With this concept, we would not need to define two methods (one for
int, one for