type
StoreInt = ref object of RootObj
val: int
dep : seq[StoreKind]
req : seq[StoreKind]
StoreFloat = ref object of RootObj
val : float
dep : seq[StoreKind]
req : seq[StoreKind]
StoreString = ref object of RootObj
val : string
dep : seq[StoreKind]
req : seq[StoreKind]
StoreKind = StoreInt|StoreFloat|StoreString
var a = StoreInt(val : 5, dep: @[], req: @[])
This code gives me the error invalid type 'StoreKind' in this context: 'StoreInt'
I know the code below works.
StoreVariable = ref object of RootObj
case kind : NodeKind
of nkInt: intVal: int
of nkFloat: floatVal: float
of nkString: strVal: string
dep : seq[StoreVariable]
req : seq[StoreVariable]
but I wanted to use it with a converter like so
converter toInt(x: StoreInt): int = x.val
type
Store = ref object of RootObj
dep: seq[Store]
req: seq[Store]
StoreInt = ref object of Store
val: int
StoreFloat = ref object of Store
val: float
StoreString = ref object of Store
val: string
type
StoreKind = enum StoreInt, StoreFloat, StoreString
Store = ref object of RootObj
case kind: StoreKind
of StoreInt: intVal: int
of StoreFloat: floatVal: float
of StoreString: strVal: string
dep: seq[Store]
req: seq[Store]
var a = Store(kind: StoreInt, intVal : 5, dep: @[], req: @[])
Well, you could do this:
type
StoreInt = ref object of RootObj
val: int
dep : seq[StoreVariable]
req : seq[StoreVariable]
StoreFloat = ref object of RootObj
val : float
dep : seq[StoreVariable]
req : seq[StoreVariable]
StoreString = ref object of RootObj
val : string
dep : seq[StoreVariable]
req : seq[StoreVariable]
StoreKind = enum
skFloat
skInt
skString
StoreVariable = ref object of RootObj
case kind : StoreKind
of skInt: intVal: StoreInt
of skFloat: floatVal: StoreFloat
of skString: strVal: StoreString
converter toInt(x: StoreInt): int = x.val
And I do realize it's probably not what you want, because it doesn't give you the delicious automatic conversion magic when you pull values out of the dep/req seqs, but the thing is, that wouldn't work no matter what, because putting different things into the same container inherently involves loss of static type information.Do you perhaps want it like this?
type
Store[T] = ref object of RootObj
val: T
dep: seq[Store[T]]
StoreInt = Store[int]
converter toInt[T: int](x: Store[T]): T = x.val
var a = StoreInt(val: 5, dep: @[])
echo a.toInt
Thx for the help. One more question : is there any way to forward declare a variable without knowing the exact type?
if flag == true:
var c = 5
else:
var c = 10.0
The if statements here open a new scope so I no longer have access to the c variable. I was thinking I could work around this with some kind of template maybe.
use when , as long the variable can be know at compile time
import typetraits
const flag = true
when flag == true:
var c = 5
else:
var c = 10.0
echo name(type(c))
take a note that's only for compile time, you cannot switch during runtime