|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching * Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
templatesA template is essentially a textual substitution mechanism. When the compiler encounters a template call, it replaces it inline with the template's body, substituting the arguments. No function call — it's as if you typed the code out by hand. Reach for a func / proc by default, upgrade to a template when you need compile-time inlining or syntactic sugar, and escalate to a macro only when templates aren't expressive enough. Example 1template square(x: int): int = x * x echo square(5) # becomes: echo 5 * 5 𝥶Here a proc or func would be a better choice! I only wanted to demonstrate the textual substitution with this. A return value (int) is specified since we use it as an expression: let value = square(10) echo value # 100 Example 2: repeat
No return value is specified for the template since we don't want to use it as an expression. Output: hello hello hello Example 3: timerimport std/os # sleep import std/strutils # format import std/times # epochTime # class Timer ############################################################### type Timer* = ref object start: float stop: float proc elapsedTime*(self: Timer): float = self.stop - self.start # ########################################################################### template withTimer*(timer: Timer, body: untyped) = timer.start = epochTime() body timer.stop = epochTime() # ########################################################################### proc main() = let timer = Timer() withTimer(timer): sleep(2_000) # 2 seconds echo "Elapsed time: $1 sec".format(timer.elapsedTime) main() Output: Elapsed time: 2.0001296997070312 sec Exercise
|
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |
||||