This is your safest bet:
    
    
    template Cast(T: typedesc, value: untyped): untyped =
      cast[T](value)
    
    echo Cast(int, 3)
    
    
    Run

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
    
    
    Run

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)
    
    
    Run

Like before, if you're on 0.19, you can replace `typedesc[T]` with `type T`.

Reply via email to