Anonymous user
Constrained genericity: Difference between revisions
→{{header|Ada}}: I think this solves the issue
(Removed assertion that this language features applies only to statically typed languages. (see J implementation for counter example.)) |
(→{{header|Ada}}: I think this solves the issue) |
||
Line 6:
=={{header|Ada}}==
Ada allows various constraints to be specified in parameters of
<lang ada>with Ada.Containers.Indefinite_Vectors;
Line 14:
procedure Eat (Object : in out Food) is abstract;
package Food_Boxes is▼
with Ada.Containers;
with Nutrition;
generic
type New_Food is new Nutrition.Food;
package Food_Vectors is
new Ada.Containers.Indefinite_Vectors
( Index_Type => Positive,
Element_Type =>
);
subtype Food_Box is
▲end Nutrition;</lang>
The package Nutrition defines an interface of an eatable object, that is, the procedure Eat. Then a container package is instantiated with the elements to be of the class Food. I.e. the elements can be only the members of the class Food. Example of use:▼
end Food_Boxes;
</lang>
▲The package Nutrition defines an interface of an eatable object, that is, the procedure Eat. Then a generic container package is
<lang ada>type Banana is new Food with null record;
overriding procedure Eat (Object : in out Banana) is null;
package Banana_Box is new Food_Boxes (Banana);
type Tomato is new Food with null record;
overriding procedure Eat (Object : in out Tomato) is null;
package Tomato_Box is new Tomato_Boxes (Tomato);
-- We have declared Banana and Tomato as a Food.
</lang>
The Tomato_Box can only contain tomatoes; the Banana_Box can only contain bananas. You can only create boxes of eatable objects.
=={{header|C sharp|C#}}==
|