C++ Templates Tutorial

C++ templates allow you to write generic and reusable code that works with different data types. Templates provide type safety while maintaining flexibility.

Function Templates

Function templates are used to create a single function that operates on different data types:


#include <iostream>
using namespace std;

template <typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    cout << add(3, 4) << endl;        // Integer addition
    cout << add(3.5, 4.5) << endl;  // Floating-point addition
    return 0;
}
                

Class Templates

Class templates are used to define generic classes:


#include <iostream>
using namespace std;

template <typename T>
class Box {
private:
    T value;
public:
    Box(T val) : value(val) {}
    T getValue() { return value; }
};

int main() {
    Box<int> intBox(42);
    Box<string> strBox("Template");

    cout << intBox.getValue() << endl;
    cout << strBox.getValue() << endl;
    return 0;
}
                

Template Specialization

You can create specialized versions of templates for specific data types:


#include <iostream>
using namespace std;

template <typename T>
class Box {
public:
    void print() { cout << "Generic template" << endl; }
};

template ><
class Box<int> {
public:
    void print() { cout << "Specialized for int" << endl; }
};

int main() {
    Box<int> intBox;
    Box<float> floatBox;

    intBox.print();
    floatBox.print();
    return 0;
}
                

Advantages of Templates

  • Code reusability for different data types.
  • Type safety with compile-time checks.
0 Interaction
2.3K Views
Views
30 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home