Hi all, I am trying to learn templates but i coudnt get the idea of templates easily. My aim is to mimic the cast function. Please look this --
template Cast(tp : typed, value : typed) = cast[tp](value) # Failed
template Cast[T](tp : T, value : typed) = cast[tp](value) # Failed
template Cast(tp : [T], value : typed) = cast[tp](value) # Failed
All i want to tell the compiler is -
template Cast( tp : is_a_generic_type, value : any_typed_value) = cast[ _generic_type](typed_value)
How to do it ? Any help ?This is your safest bet:
template Cast(T: typedesc, value: untyped): untyped =
cast[T](value)
echo Cast(int, 3)
To explain the template parameter types, typedesc (or just type is enough if you're on 0.19) matches type descriptors, so things like int, Exception, seq, Slice[int] and whatnot. untyped matches any AST expression and no type checking is performed on it, so you can do things like:
template foo(ex: untyped) =
var a {.inject.} = 3 # {.inject.} passes the variable `a` to `ex`
echo ex
foo(a * 4) # 12
On the other hand, templates can also have generics, so you can do:
template Cast[T](_: typedesc[T], value: untyped): T =
cast[T](value)
echo Cast(int, 3)
Like before, if you're on 0.19, you can replace typedesc[T] with type T.
I want to install 0.19 but i am afraid that whether my current code will work or not.
0.19 brings lots of improvements and bugfixes, my recommendation would be to use it.
And if you want to have multiple versions installed, and you want to easily switch between them: choosenim is your friend.
I didn't know you could do this, but apparently this works as well (tried on both 0.18.0 and 0.19.0).
type
MyType = distinct int
template Cast[T](value: typed): T =
cast[T](value)
let a = Cast[int](3.MyType)
echo a
# prints 3
I want to install nim 0.19 but i think either i did something wrong or something happened wrong. After installing choosenim, i have a folder in my pc like this--
C:\Users\Vinod\.choosenim\toolchains\nim-0.19.0
But if i type "nim" in CMD, it seems that the version is still 0.18. Horribile. Ha ha, Those comments raising a question in my mind, especially Araq's comment. He said
Sorry, but I don't want sugar for this sharp knife. cast is the most dangerous feature of Nim, it's deliberately designed to be ugly.
How do we do type casting without danger ?But the problem is, i am expecting the program to do it automatically.
PATH is a user environment variable. I haven't seen any program installation modify that var. And that's a good thing.
I haven't used choosenim (as it doesn't work on my OS), but may be it should display something like "nim binary is installed at /foo/bar/bin/", and that the user should add that to their path themselves.
See how PATH update instructions are added to Go installation too.
How do we do type casting without danger ?
When you know what you're doing. Most of the time you would want to convert the type instead, which should be safe and can be done with TypeName(expression)