Constrained genericity: Difference between revisions

Content added Content deleted
(added Morfa)
Line 596: Line 596:
<lang java5>test.<EatableClass>bar();</lang>
<lang java5>test.<EatableClass>bar();</lang>
The <code>foo</code> method from before can figure out <code>T</code> from its parameter, but this <code>bar</code> method needs to be told what T is.
The <code>foo</code> method from before can figure out <code>T</code> from its parameter, but this <code>bar</code> method needs to be told what T is.

=={{header|Morfa}}==
{{trans|D}}
===Template Version===
<lang morfa>import morfa.type.traits;

template < T >
alias IsEdible = HasMember< T, "eat" >;

template < T >
if (IsEdible< T >)
struct FoodBox
{
var food: T[];
}

struct Carrot
{
func eat(): void {}
}

struct Car {}

func main(): void
{
var carrotBox: FoodBox< Carrot >; // OK
carrotBox.food ~= Carrot(); // Adds a carrot

// var carBox: FoodBox< Car >; // Not allowed
static assert( not trait(compiles, func() { var carBox: FoodBox< Car >; } ));
}</lang>


===Interface Version===

<lang morfa>interface IEdible
{
public func eat(): void;
}

template < T >
if (IsBaseOf< T, IEdible >)
struct FoodBox
{
var food: T[];
}

class Carrot: IEdible
{
public override func eat(): void {}
}

class Car {}

func main(): void
{
var carrotBox: FoodBox< Carrot >; // OK
// var carBox: FoodBox< Car >; // Not allowed
static assert( not trait(compiles, func() { var carBox: FoodBox< Car >; } ));
}</lang>


=={{header|Nemerle}}==
=={{header|Nemerle}}==