No shortcircuit for static if or template constraints?
stewart via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Oct 24 16:26:07 PDT 2015
Hi All,
Given this code:
---
import std.traits;
import std.range;
import std.stdio;
enum isSupportedRange(T) = (isInputRange!T &&
isIntegral!(ForeachType!T));
void func(T)(T vals)
{
static if(isSupportedRange!T) {
// Do something with a range
} else {
// Do something with a scalar
}
}
void main() {
int a1 = 0;
int[] a2 = [1,2,3];
func(a1);
func(a2);
}
---
I a compile error like so:
...std/traits.d(6136): Error: invalid foreach aggregate 0
hack.d(6): Error: template instance std.traits.ForeachType!int
error instantiating
hack.d(10): instantiated from here: isSupportedRange!int
hack.d(22): instantiated from here: func!int
However, if I remove the Foreach part the "isInputRange!T"
clearly fails.
I also tried overloading the function like so:
---
enum isSupportedRange(T) = (isInputRange!T &&
isIntegral!(ForeachType!T));
void func(T)(T vals) if(isSupportedRange!T) {
// Do something with a range
}
void func(T)(T vals) if(isNumeric!T) {
// Do something with a scalar
}
---
Again, if I remove the Foreach part and ignore element type of
the range it works OK.
Am I doing something wrong?
Thanks,
stew
More information about the Digitalmars-d-learn
mailing list