Page 1 of 1

Generic constraints

PostPosted: Tue Aug 06, 2013 6:35 am
by Chasm
How do I define constraints like in D?

Let's say I need a Foo that can operate on ints, floats and doubles only.

Re: Generic constraints

PostPosted: Tue Aug 06, 2013 6:37 am
by Chasm
Can't I specify D-like constraints?

struct Foo<of T>
where T must be int16, uint16, int32, uint32, int64, uint64, float, double
pass

Why the hell not?

Re: Generic constraints

PostPosted: Tue Aug 06, 2013 9:09 am
by Charles
Cobra's generics ride on top of .NET/CLR generics. And yes, you can constrain generics. Unfortunately, you cannot constrain them to a numeric type and then use math operators though if you only need comparisons you can use IComparable or IEquatable. I've thought of ways that Cobra might get around this, but none of them were pretty.

See:
http://cobra-language.com/trac/cobra/br ... 0-generics
https://www.google.com/search?q=C%23+co ... +to+number

Re: Generic constraints

PostPosted: Tue Aug 06, 2013 10:29 am
by Chasm
That is disappointing, I absolutely hate the C# constraints as they prove to be mostly useless.

Re: Generic constraints

PostPosted: Tue Aug 06, 2013 8:15 pm
by Charles
While I'm also disappointed with the inability to provide numeric constraints, I don't otherwise find the constraints useless. What they let you do is invoke specific methods and properties on the objects. For example, in Cobra's own compiler source code we have:
class Container<of TMember>
is abstract, partial
where TMember must be class, IMember
inherits NamedNode
implements IContainer, IType
...

The constraint is the line with "must be" and it's necessary for the Container class' implementation (unless we went dynamic with everything, but that sacrifices speed and compile-time error checking).