Free tutorials & notes in Hindi & English · Clean code examples · Mobile friendly learning
🔴 Advanced  ·  Lesson 51

Templates in C++

Written and reviewed by · Senior IT Faculty · 15+ years’ experience

What are templates?

Templates let you write code once that works for any type. Instead of writing a separate max for int, double and string, you write one template and the compiler makes each version you need. This is called generic programming.

Function templates

Put template <typename T> before the function and use T as the type:

C++
#include <iostream>
using namespace std;
template <typename T>
T maxOf(T a, T b) {
    return (a > b) ? a : b;
}
int main() {
    cout << maxOf(3, 7) << "\n";        // int
    cout << maxOf(2.5, 1.5) << "\n";    // double
    cout << maxOf('a', 'z') << "\n";    // char
    return 0;
}
Output:
7
2.5
z

The compiler deduces T from the arguments each time.

Multiple type parameters

C++
template <typename A, typename B>
void show(A a, B b) {
    cout << a << " and " << b << "\n";
}
// show(1, "hi");  → int and string

Class templates

A class template makes a whole class generic — perfect for containers:

C++
template <typename T>
class Box {
    T value;
public:
    Box(T v) : value(v) {}
    T get() { return value; }
};
int main() {
    Box<int> a(42);
    Box<string> b("hello");
    cout << a.get() << " " << b.get();   // 42 hello
}
Output:
42 hello

Here you specify the type explicitly: Box<int>, Box<string>. For a compact syntax reference, see the templates syntax page.

Templates and the STL

The entire Standard Template Library is built on templates. That is why vector<int>, vector<string> and map<string,int> all come from the same generic code, and algorithms like sort work on any suitable container.

How templates work

A template is not code by itself — it is a recipe. When you use it with a type, the compiler instantiates it, generating a concrete version for that type. Unused templates generate nothing.

Common mistakes

  • Forgetting template <typename T> before the definition.
  • Expecting the compiler to deduce a class template's type (you often specify it).
  • Using a type with the template that lacks a needed operator (e.g. > in maxOf).
  • Splitting a template's declaration and definition across files carelessly.
🏋️ Practice

Write a function template sumArray(T arr[], int n) that returns the sum of any numeric array. Then write a class template Pair<A,B> that stores two values of different types and prints them.

Summary

  • Templates write code once that works for any type.
  • Function templates deduce the type from the arguments.
  • Class templates need the type specified, like Box<int>.
  • The compiler instantiates a concrete version per type used.
  • The STL is built entirely from templates.

Frequently Asked Questions

What are templates in C++?
Templates let you write generic code that works with any data type, without rewriting it for each type. You define a function or class once with a placeholder type parameter, and the compiler generates a specific version for each type you actually use.
What is the difference between a function template and a class template in C++?
A function template generates a function for whatever type you call it with, such as a generic max that works on ints or doubles. A class template generates a whole class for a type, such as a container that can hold any element type, which is how the STL builds vector and similar types.
How do you write a function template in C++?
You precede the function with template <typename T> and then use T as the type inside, for example template <typename T> T maxOf(T a, T b). When you call it, the compiler deduces T from the arguments and creates the matching version.
What is the difference between typename and class in a template in C++?
In a template parameter list, typename and class mean exactly the same thing, so template <typename T> and template <class T> are interchangeable. Many programmers prefer typename because it reads more clearly for any type, not just class types.
How does the C++ Standard Template Library use templates?
The Standard Template Library is built entirely from templates, so containers like vector, map and set, and algorithms like sort, work with any suitable type. This is why you can have a vector<int> or a vector<string> from the same template code.

Templates क्या हैं?

Templates आपको एक बार ऐसा code लिखने देते हैं जो किसी भी type के लिए काम करे। int, double और string के लिए अलग max लिखने के बजाय, आप एक template लिखते हैं और compiler हर version बनाता है जो आपको चाहिए। इसे generic programming कहते हैं।

Function templates

Function से पहले template <typename T> लगाएँ और T को type के रूप में इस्तेमाल करें:

C++
#include <iostream>
using namespace std;
template <typename T>
T maxOf(T a, T b) {
    return (a > b) ? a : b;
}
int main() {
    cout << maxOf(3, 7) << "\n";        // int
    cout << maxOf(2.5, 1.5) << "\n";    // double
    cout << maxOf('a', 'z') << "\n";    // char
    return 0;
}
Output:
7
2.5
z

Compiler हर बार arguments से T निकालता है।

कई type parameters

C++
template <typename A, typename B>
void show(A a, B b) {
    cout << a << " and " << b << "\n";
}
// show(1, "hi");  → int and string

Class templates

Class template पूरी class को generic बनाता है — containers के लिए एकदम सही:

C++
template <typename T>
class Box {
    T value;
public:
    Box(T v) : value(v) {}
    T get() { return value; }
};
int main() {
    Box<int> a(42);
    Box<string> b("hello");
    cout << a.get() << " " << b.get();   // 42 hello
}
Output:
42 hello

यहाँ आप type स्पष्ट रूप से बताते हैं: Box<int>, Box<string>। संक्षिप्त syntax reference के लिए, templates syntax page देखें।

Templates और STL

पूरी Standard Template Library templates पर बनी है। इसीलिए vector<int>, vector<string> और map<string,int> सब एक ही generic code से आते हैं, और sort जैसे algorithms किसी भी उपयुक्त container पर काम करते हैं।

Templates कैसे काम करते हैं

Template अपने आप में code नहीं है — यह एक नुस्खा है। जब आप इसे किसी type के साथ इस्तेमाल करते हैं, compiler इसे instantiate करता है, उस type के लिए एक concrete version बनाते हुए। अप्रयुक्त templates कुछ नहीं बनाते।

आम गलतियाँ

  • Definition से पहले template <typename T> भूलना।
  • यह उम्मीद करना कि compiler class template का type निकालेगा (आप अक्सर इसे बताते हैं)।
  • Template के साथ ऐसा type इस्तेमाल करना जिसमें ज़रूरी operator न हो (जैसे maxOf में >)।
  • Template की declaration और definition को files में लापरवाही से बाँटना।
🏋️ अभ्यास

एक function template sumArray(T arr[], int n) लिखें जो किसी भी numeric array का योग लौटाए। फिर एक class template Pair<A,B> लिखें जो अलग types की दो values रखे और उन्हें print करे।

सारांश

  • Templates एक बार ऐसा code लिखते हैं जो किसी भी type के लिए काम करे।
  • Function templates arguments से type निकालते हैं।
  • Class templates को type बताना पड़ता है, जैसे Box<int>
  • Compiler हर इस्तेमाल किए type के लिए एक concrete version बनाता है।
  • STL पूरी तरह templates से बनी है।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.