Hi,
why does this not compile:
proc traitIsObject(x: object): Bool {.noSideEffect.} =
return true
proc traitIsObject[T: tuple|enum|proc|ref|ptr|var|distinct|array|set|seq] (x: T): Bool {.noSideEffect.} =
return false
type
TTest = object
a: Int
var a: TTest
when traitIsObject(a):
echo "a is object"
aborts with Error: constant expression expected
Bug report please.
Edit: Zahary is right, I missed the variable thing.
There is no bug here.
the a variable is not a compile-time value and cannot be used within a when statement.
To achieve the desired effect, you can use a C++ style trick:
type
TTrue = object
TFalse = object
proc traitIsObject(T: object): TTrue = nil
proc traitIsObject[T: tuple|enum|proc|ref|ptr|var|distinct|array|set|seq](x: T): TFalse = nil
type
TTest = object
a: Int
var a: TTest
var b: seq[int]
when traitIsObject(b).type is TTrue:
echo "a is object"
or you can use a typedesc param (so the function will accept a type instead of value):
proc isObject(T: typedesc{object}): bool = return true
proc isObject(T: typedesc{tuple|enum|proc|ref|ptr|var|distinct|array|set|seq}): bool = return false
when a.type.isObject:
echo "a is object"
typedesc params are relatively new and unfortunately not documented yet, but the code should be self-explanatory.