How do I define constraints like in D?
Let's say I need a Foo that can operate on ints, floats and doubles only.
Forums
Generic constraints
5 posts
• Page 1 of 1
Re: Generic constraints
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?
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
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
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
That is disappointing, I absolutely hate the C# constraints as they prove to be mostly useless.
- Chasm
- Posts: 33
Re: Generic constraints
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:
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).
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
5 posts
• Page 1 of 1
Who is online
Users browsing this forum: No registered users and 44 guests