🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Templates: function and class templates

Write function and class templates that take the type as a parameter, instead of writing the same code again and again for int, double and other types. Example: a type-independent clamp function and a fixed-size ring buffer.

You need to squeeze an ADC reading into the 0-1023 range, a voltage into 0-3.3 V and a motor speed into 0-3000 rpm. The logic is the same for all three: if the value is below the lower limit, return the lower limit; if it is above the upper limit, return the upper limit. With the overloading you learned in the functions lesson you could write a separate version for each type, but three copies mean three chances for a bug. Fix one and forget the others, and your program becomes inconsistent. C++'s answer is the template: you write the code once, leave the type as a parameter, and the compiler generates the code for every type you need. In fact, you are already using templates: std::vector<double> and std::map<std::string, int> are class templates.

Function templates

A template starts with a template <typename T> line in front of the function. Here T means "a type that is not known yet"; you can name it anything, but T is the convention.

#include <iostream>
#include <string>

template <typename T>
T sinirla(T deger, T alt, T ust) {
    if (deger < alt) return alt;
    if (deger > ust) return ust;
    return deger;
}

template <typename T>
T enBuyuk(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    std::cout << sinirla(1100, 0, 1023) << '\n';      // int: ADC okumasi
    std::cout << sinirla(3.47, 0.0, 3.3) << '\n';     // double: gerilim
    std::cout << sinirla(-5, 0, 100) << '\n';
    std::cout << enBuyuk<double>(4, 2.5) << '\n';      // tip acikca verildi
    std::cout << enBuyuk(std::string("led"), std::string("direnc")) << '\n';
    return 0;
}
1023
3.3
0
4
led

In the first call all three arguments are int, so the compiler works out on its own that T is int; this is called template argument deduction. In the second call T becomes double. On the fourth line the arguments are 4 (int) and 2.5 (double), so the compiler cannot pick a single T; that is why we gave the type ourselves in angle brackets: enBuyuk<double>. The last line compares text: for std::string, > looks at alphabetical order, and "led" comes after "direnc".

In a real project you do not need to write your own clamp function: C++17 added std::clamp(value, low, high) to the <algorithm> header. We wrote our own here to see how templates work.

What does the compiler actually do?

A template is not code that runs on its own; it is a pattern. When the compiler sees the call sinirla(1100, 0, 1023), it replaces every T in the pattern with int and generates a real function named sinirla<int>. This is called instantiation. The program above generated four separate functions: sinirla<int>, sinirla<double>, enBuyuk<double> and enBuyuk<std::string>.

This has two important consequences:

  • There is no extra cost at run time. The generated code is the same as an int version written by hand. That is why templates are used freely in embedded systems too.
  • The type must support the operations the template uses. We used < and > inside sinirla. If you call it with a struct that lacks these operators, the compiler reports an error during instantiation. These error messages can be long; read the part at the top and the part that says "required from here" and points at your line.

A class template: a fixed-size ring buffer

In the mini project we said a real device would keep its readings in a ring buffer: memory never grows, and when the buffer is full the oldest reading is overwritten. We want to use this structure for both double temperatures and int ADC values, and we want to choose the size at compile time. A class template does both:

#include <array>
#include <cstddef>
#include <initializer_list>
#include <iostream>

template <typename T, std::size_t N>
class HalkaTampon {
public:
    void ekle(T deger) {
        veri_[bas_] = deger;
        bas_ = (bas_ + 1) % N;        // sona gelince basa don
        if (adet_ < N) ++adet_;
    }

    std::size_t adet() const { return adet_; }

    T ortalama() const {
        T toplam{};
        for (std::size_t i = 0; i < adet_; ++i) toplam += veri_[i];
        return adet_ ? toplam / static_cast<T>(adet_) : T{};
    }

private:
    std::array<T, N> veri_{};
    std::size_t bas_ = 0;
    std::size_t adet_ = 0;
};

int main() {
    HalkaTampon<double, 4> sicaklik;
    for (double s : {21.0, 22.0, 23.0, 24.0, 25.0, 26.0}) {
        sicaklik.ekle(s);
    }
    std::cout << "Adet: " << sicaklik.adet() << '\n';
    std::cout << "Son 4 ortalama: " << sicaklik.ortalama() << '\n';

    HalkaTampon<int, 3> adc;
    adc.ekle(510);
    adc.ekle(514);
    std::cout << "ADC ortalama: " << adc.ortalama() << '\n';
    return 0;
}
Adet: 4
Son 4 ortalama: 24.5
ADC ortalama: 512

Let's read the code piece by piece:

  • template <typename T, std::size_t N>: the template has two parameters. T is a type and N is a number. This non-type parameter is a constant known at compile time, so it can be used as the size of a fixed-size array such as std::array<T, N>. No heap is used, so it is safe on a microcontroller as well.
  • T toplam{}: the braces give the "zero value" whatever the type is: 0 for int, 0.0 for double.
  • Six values were added, but the buffer holds four. 25 and 26 overwrote the two oldest values, 21 and 22; the buffer now holds 25, 26, 23, 24. Their average is 98 / 4 = 24.5.
  • For HalkaTampon<int, 3> the average is computed with integer division: 1024 / 2 = 512. If the sum had been 1023, the fraction would have been dropped. The template applies the rules of the type you give it, exactly.

To the compiler, HalkaTampon<double, 4> and HalkaTampon<double, 8> are two different types; you cannot assign one to the other. This may look like a restriction, but it catches size mismatches at compile time instead of at run time.

Where do templates go?

In the classes lesson we put the declaration in a .h file and the definition in a .cpp file. That split does not work for templates: to instantiate a template, the compiler must see its full body at the point where it is called. So the whole template goes into the header file. This is also why standard headers such as <vector> and <algorithm> contain thousands of lines of code.

Common mistakes

  • Calling with mixed types. sinirla(3.47, 0, 3.3) does not compile: the first and last arguments are double, the middle one is int; the compiler cannot pick a single type for T ("deduced conflicting types"). Either write 0.0 or give the type explicitly: sinirla<double>(...).
  • Putting the template body in a .cpp file. The code compiles, but the linker says "undefined reference", because the body was not visible while main.cpp was being compiled and no instantiation could happen. Move the whole template into the header file.
  • Forgetting that an explicit type causes silent conversion. If you write kare<int>(2.5), 2.5 is converted to int first (it becomes 2) and the result is 4. When you write an explicit type, remember that the arguments will be converted to it.

Exercise

Write a class template MinMax<T> that keeps track of the smallest and largest values it receives. The ekle(T) (add) method takes a new value; enKucuk() and enBuyuk() return the results. When the first value arrives, both must become that value. Try the template with three different types: int ADC readings, double currents and std::string circuit labels.

Hint: keep a bool bos_ = true; member to tell the first value apart. If you compare with bos_ || deger < enKucuk_, the first value is always accepted. Since the template only uses < and >, it works with text as well.

Solution

#include <initializer_list>
#include <iostream>
#include <string>

template <typename T>
class MinMax {
public:
    void ekle(T deger) {
        if (bos_ || deger < enKucuk_) enKucuk_ = deger;
        if (bos_ || deger > enBuyuk_) enBuyuk_ = deger;
        bos_ = false;
    }
    bool bos() const { return bos_; }
    T enKucuk() const { return enKucuk_; }
    T enBuyuk() const { return enBuyuk_; }

private:
    T enKucuk_{};
    T enBuyuk_{};
    bool bos_ = true;
};

int main() {
    MinMax<int> adc;
    for (int x : {512, 498, 530, 505}) adc.ekle(x);
    std::cout << "ADC: " << adc.enKucuk() << " - " << adc.enBuyuk() << '\n';

    MinMax<double> akim;
    for (double x : {1.8, 2.4, 0.9, 3.1}) akim.ekle(x);
    std::cout << "Akim: " << akim.enKucuk() << " - " << akim.enBuyuk() << " A\n";

    MinMax<std::string> etiket;
    for (const char* s : {"R12", "C3", "U1"}) etiket.ekle(s);
    std::cout << "Etiket: " << etiket.enKucuk() << " - " << etiket.enBuyuk() << '\n';
    return 0;
}
ADC: 498 - 530
Akim: 0.9 - 3.1 A
Etiket: C3 - U1

You wrote one class and the compiler generated three separate classes from it. Among the labels, "C3" comes first alphabetically and "U1" last, hence the result.

In short, templates let you write type-independent code once and get safe, fast copies for each type at compile time. In the next lesson we go back to memory management and take a deep look at smart pointers; you will see that they are class templates too.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. Why does the call sinirla(3.47, 0, 3.3) not compile? (sinirla is a function template whose three parameters are all T)
2. In the template template <typename T, std::size_t N> class HalkaTampon, which statement about N is true?
3. You put a function template's declaration in a .h file and its body in a separate .cpp file, then called it from another file. What is the most likely result?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.