generated at
Nimのtemplate



template
Cのプリプロセッサと同等のもの(?)
独自のスコープを持つ

typeを作るときには、injectが必要。これがないとコンパイルできない

使用例
関数の生成
「タグを出力する関数」を定義するtemplate
Nim
template htmlTag(tag): untyped = proc tag(): string = "<" & astToStr(tag) & ">" htmlTag(br) # br()関数が作成される echo br() # <br>

サンプルコード
nim
# https://qiita.com/snowlt23/items/f50ab84afeab9469e422#template template withFile(f, fn, mode, actions: untyped): untyped = var f: File if open(f, fn, mode): try: actions finally: close(f) else: quit("cannot open: " & fn) withFile(txt, "Rabbit.txt", fmWrite): txt.writeLine("BlueMountain") txt.writeLine("Mocha")
サンプルコード2
あんまわからん。リンク先参照
nim
# https://hookrace.net/blog/introduction-to-metaprogramming-in-nim/#templates import strutils, times, os, strformat type Level* {.pure.} = enum debug, info, warn, error, fatal var logLevel* = Level.debug proc expensiveDebuggingInfo*: string = sleep(milsecs = 1000) result = "Everything looking good!" # # 普通の関数を使う場合 # proc debug*(args: varargs[string, `$`]) = # if logLevel <= Level.debug: # echo fmt"[{getDateStr()} {getClockStr()}]: {join args}" # templateを使う場合 template debug*(args: varargs[string, `$`]) = if logLevel <= Level.debug: const module = instantiationInfo().filename[0 .. ^5] echo fmt"[{getDateStr()} {getClockStr()}][$#]: $#" % [module, join args] debug expensiveDebuggingInfo()
参考