Forums

Generic constraints

General discussion about Cobra. Releases and general news will also be posted here.
Feel free to ask questions or just say "Hello".

Generic constraints

Postby Chasm » Tue Aug 06, 2013 6:35 am

How do I define constraints like in D?

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

Re: Generic constraints

Postby Chasm » Tue Aug 06, 2013 6:37 am

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?
Chasm
 
Posts: 33

Re: Generic constraints

Postby Charles » Tue Aug 06, 2013 9:09 am

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
Charles
 
Posts: 2515
Location: Los Angeles, CA

Re: Generic constraints

Postby Chasm » Tue Aug 06, 2013 10:29 am

That is disappointing, I absolutely hate the C# constraints as they prove to be mostly useless.
Chasm
 
Posts: 33

Re: Generic constraints

Postby Charles » Tue Aug 06, 2013 8:15 pm

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).
Charles
 
Posts: 2515
Location: Los Angeles, CA


Return to Discussion

Who is online

Users browsing this forum: No registered users and 112 guests