3

是否有可能在 a 中获取表达式(或标识符)的字符串表示形式template?例如,有下一个代码:

template `*`*(name: expr) {.immediate.} =
  var `name`* {.inject.}: string = ""
  # Want to print 'name' here, not its value like with backticks

name是否可以在模板中获取表达式的字符串表示形式?

4

1 回答 1

6

您可以使用astToStr系统模块中的魔法来执行此操作:

template foo*(name: untyped) =
  var `name`* {.inject.}: string = ""
  # Want to print 'name' here, not its value like with backticks
  echo "the variable name is ", name.astToStr

foo test

输出将是:

the variable name is test

immediate最新版本的编译器不鼓励使用pragma。有关更多详细信息,请参阅以下答案: 模板和宏中的 typed vs untyped vs expr vs stmt

于 2015-07-23T12:03:33.533 回答