Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ◇C++, ◇Clojure, ◇Scala


[ edit | logout ]
[ sandbox | passwd ]

templates

A 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 1

template 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

Kotlin's repeat
// Kotlin

fun main() {
    repeat(3) {
        println("hello")
    }
}
template repeat(times: int, body: untyped) =
  for _ in 0 ..< times:
    body

repeat(3):
  echo "hello"

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: timer

import 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

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 May 01, 20:55