LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 18 of 27

Templates

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Templates · Study material

Templates in C++ let you write a function or class once and use it with any type. std::vector<int>, std::vector<std::string>, std::sort, std::max and std::unique_ptr are all templates – the compiler generates a specialised version for each type you use, so generic code runs as fast as hand-written code. Templates are the foundation of the Standard Template Library (STL), of generic programming and of compile-time polymorphism. This page covers function templates, class templates, deduction and CTAD, non-type parameters, specialisation, variadic templates and fold expressions, if constexpr, type traits and C++20 concepts, with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – all verified on a real C++ compiler.

On this page

  • Function templates and template argument deduction
  • Class templates, member definitions and CTAD
  • Non-type and default template parameters
  • Full and partial specialisation
  • Variadic templates, fold expressions and if constexpr
  • Concepts, requires clauses, enable_if, alias and variable templates

Function templates

A function template starts with template <typename T> (or the equivalent template <class T>). When you call it, the compiler deduces T from the arguments and instantiates a real function for that type. Deduction needs every use of T to agree – largest(3, 2.5) fails – but you can always give the arguments explicitly: largest<double>(3, 2.5).

#include <iostream>
#include <string>

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

template <typename T, typename U>
auto add(T a, U b) { return a + b; }            // return type deduced from a + b

int main() {
    std::cout << largest(3, 9) << ' '                      // T = int (deduced)
              << largest(2.5, 1.5) << ' '                  // T = double
              << largest<std::string>("pear", "apple") << '\n';   // T given explicitly
    // largest(3, 2.5);   error: T cannot be both int and double
    std::cout << largest<double>(3, 2.5) << ' ' << add(1, 2.5) << ' ' << add(std::string("C"), "++") << '\n';
    return 0;
}

Output

9 2.5 pear
3 3.5 C++

Class templates

A class template is a blueprint for classes: Pair<std::string, int> and Pair<double, char> are different types. Member functions defined outside the class repeat the template header. Since C++17, class template argument deduction (CTAD) lets you omit the arguments when the constructor makes them clear.

#include <iostream>
#include <string>
#include <utility>

template <typename K, typename V>
class Pair {
    K key_;
    V value_;
public:
    Pair(K k, V v) : key_(std::move(k)), value_(std::move(v)) {}
    const K& key() const { return key_; }
    const V& value() const { return value_; }
    void print() const;                          // defined outside the class below
};

template <typename K, typename V>
void Pair<K, V>::print() const { std::cout << key_ << " => " << value_ << '\n'; }

int main() {
    Pair<std::string, int> a("marks", 91);       // arguments written out
    Pair b("city", std::string("Pune"));         // C++17 CTAD: Pair<const char*, std::string>
    Pair c(3.5, 'x');                            // Pair<double, char>
    a.print(); b.print(); c.print();
    return 0;
}

Output

marks => 91
city => Pune
3.5 => x

Non-type and default template parameters

Template parameters can also be compile-time values – integers, enums, pointers and, since C++20, some class types – as in std::array<int, 5>. Parameters can have defaults, like function parameters.

#include <iostream>
#include <string>

// N is a compile-time value; T has a default
template <std::size_t N, typename T = int>
class FixedStack {
    T data_[N]{};
    std::size_t size_ = 0;
public:
    bool push(const T& x) { if (size_ == N) return false; data_[size_++] = x; return true; }
    T pop() { return data_[--size_]; }
    static constexpr std::size_t capacity() { return N; }
};

template <int Base>
int digits(int n) { int d = 1; while (n >= Base) { n /= Base; ++d; } return d; }

int main() {
    FixedStack<3> s;                              // FixedStack<3, int>
    for (int i = 1; i <= 5; ++i) std::cout << s.push(i * 10);
    std::cout << ' ' << s.pop() << ' ' << FixedStack<8, std::string>::capacity() << '\n';
    std::cout << digits<10>(2025) << ' ' << digits<2>(255) << ' ' << digits<16>(255) << '\n';
    return 0;
}

Output

11100 30 8
4 8 2

Template specialisation

A full specialisation (template <>) gives a separate implementation for one exact set of arguments. A partial specialisation covers a family, such as "every pointer type" – partial specialisation is allowed for class templates only; for functions, use overloading.

#include <cstring>
#include <iostream>
#include <string>

// Primary template
template <typename T>
struct TypeName { static std::string get() { return "unknown"; } };

// Full specialisations
template <> struct TypeName<int>    { static std::string get() { return "int"; } };
template <> struct TypeName<double> { static std::string get() { return "double"; } };

// Partial specialisation: any pointer type
template <typename T>
struct TypeName<T*> { static std::string get() { return TypeName<T>::get() + "*"; } };

// Function template with a full specialisation for C strings
template <typename T>
bool equal(T a, T b) { return a == b; }
template <>
bool equal<const char*>(const char* a, const char* b) { return std::strcmp(a, b) == 0; }

int main() {
    std::cout << TypeName<int>::get() << ' ' << TypeName<double**>::get() << ' ' << TypeName<char>::get() << '\n';
    char buf[] = "hi";
    const char* p = buf;
    std::cout << equal(3, 3) << equal<const char*>(p, "hi") << '\n';
    return 0;
}

Output

int double** unknown
11

Variadic templates and fold expressions

A parameter pack (typename... Ts) accepts any number of template arguments. sizeof...(Ts) counts them, xs... expands them, and C++17 fold expressions such as (xs + ...) combine them with an operator. This is how std::make_unique, std::tuple and std::format work.

#include <iostream>
#include <string>

// Fold expressions (C++17): apply an operator across a parameter pack
template <typename... Ts>
auto sum(Ts... xs) { return (xs + ... + 0); }

template <typename... Ts>
void print_all(const Ts&... xs) {
    ((std::cout << xs << ' '), ...);          // comma fold: print each argument in order
    std::cout << "(" << sizeof...(Ts) << " args)\n";
}

template <typename... Ts>
bool all_positive(Ts... xs) { return ((xs > 0) && ...); }

// Classic recursion, still useful to understand
void show() { std::cout << '\n'; }
template <typename T, typename... Rest>
void show(const T& first, const Rest&... rest) { std::cout << '[' << first << ']'; show(rest...); }

int main() {
    std::cout << sum(1, 2, 3, 4) << ' ' << sum() << ' ' << sum(1.5, 2) << '\n';
    print_all("Asha", 21, 'A', 8.5);
    std::cout << all_positive(3, 7, 1) << all_positive(3, -7) << '\n';
    show(1, std::string("two"), 3.0);
    return 0;
}

Output

10 0 3.5
Asha 21 A 8.5 (4 args)
10
[1][two][3]

if constexpr and type traits

<type_traits> answers questions about types at compile time (std::is_integral_v<T>, std::is_same_v<T, U> …). if constexpr uses them to choose code: the branches not taken are discarded, so they may contain code that would not compile for that T.

#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

template <typename T>
std::string describe(const T& x) {
    if constexpr (std::is_integral_v<T>)            // the untaken branches are discarded at compile time
        return "integer " + std::to_string(x);
    else if constexpr (std::is_floating_point_v<T>)
        return "real " + std::to_string(static_cast<int>(x * 100) / 100.0).substr(0, 4);
    else if constexpr (std::is_same_v<T, std::string>)
        return "text of " + std::to_string(x.size()) + " chars";
    else
        return "container of " + std::to_string(x.size());
}

int main() {
    std::cout << describe(42) << '\n' << describe(3.14159) << '\n'
              << describe(std::string("hello")) << '\n' << describe(std::vector<int>{1, 2, 3}) << '\n';
    return 0;
}

Output

integer 42
real 3.14
text of 5 chars
container of 3

Concepts (C++20)

A concept is a named, compile-time predicate on types. Constraining a template with a concept documents what it needs, rejects wrong types at the call site with a clear message, and lets overloads be chosen by what a type can do.

#include <concepts>
#include <iostream>
#include <list>
#include <string>
#include <vector>

// A named concept
template <typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;

// Three equivalent ways to constrain a template
template <Numeric T>
T square(T x) { return x * x; }

template <typename T>
    requires Numeric<T>
T cube(T x) { return x * x * x; }

auto half(Numeric auto x) { return x / 2; }           // abbreviated function template

// A concept with a requires expression
template <typename C>
concept HasSize = requires(const C& c) { { c.size() } -> std::convertible_to<std::size_t>; };

std::size_t count(const HasSize auto& c) { return c.size(); }

int main() {
    std::cout << square(7) << ' ' << cube(1.5) << ' ' << half(9) << ' ' << half(9.0) << '\n';
    std::cout << count(std::vector<int>{1, 2}) << count(std::string("abc")) << count(std::list<char>{'a'}) << '\n';
    // square(std::string("x"));   error: constraints not satisfied – Numeric<std::string> is false
    return 0;
}

Output

49 3.375 4 4.5
231

Alias templates, variable templates and typename

template <typename T> using Name = …; gives a short name to a family of types; variable templates such as pi<T> give a value per type. Inside a template, a name that depends on T and names a type (like T::value_type) must be prefixed with typename.

#include <iostream>
#include <map>
#include <string>
#include <vector>

template <typename T>
using Table = std::map<std::string, std::vector<T>>;          // alias template

template <typename T>
constexpr T pi = T(3.1415926535897932385L);                    // variable template

template <typename T>
typename T::value_type first(const T& c) { return *c.begin(); }   // 'typename': T::value_type names a type

int main() {
    Table<int> marks{{"Asha", {91, 88}}, {"Ravi", {72}}};
    std::cout << marks["Asha"][1] << ' ' << marks.size() << '\n';
    std::cout << pi<int> << ' ' << pi<float> << ' ' << pi<double> * 2 << '\n';
    std::cout << first(std::vector<char>{'z', 'y'}) << '\n';
    return 0;
}

Output

88 2
3 3.14159 6.28319
z

How templates are compiled

  • A template is not code by itself; code is generated when it is instantiated with concrete arguments.
  • The compiler needs the full definition at the point of use, so templates are normally defined entirely in header files. Defining them in a .cpp file causes "undefined reference" linker errors, unless you explicitly instantiate them.
  • Every distinct set of arguments produces a separate instantiation, which can increase binary size ("code bloat") and compile time.
  • Code that does not depend on T is checked when the template is defined; code that depends on T is checked when it is instantiated (two-phase lookup).

Common mistakes

  • Conflicting deduction – max(1, 2.5) with one T; cast, or give T explicitly.
  • Defining templates in a .cpp file – linker errors in other files.
  • Forgetting typename before dependent type names such as T::iterator.
  • Assuming operations exist – a template using < fails for types without it; state requirements with concepts.
  • Partially specialising a function template – not allowed; overload instead.
  • Using normal if instead of if constexpr – both branches must then compile for every T.

Key points to remember

  • Templates generate code per type at compile time – zero run-time overhead.
  • Function template arguments are deduced; class template arguments can be deduced with CTAD (C++17).
  • Non-type parameters are compile-time values (std::array<T, N>).
  • Full specialisation for one type; partial specialisation for families (classes only).
  • Parameter packs + fold expressions handle any number of arguments.
  • Concepts state and check requirements; if constexpr picks code by type.
  • Put template definitions in headers.

Frequently asked questions

What is the difference between typename and class in a template header?

None in template <typename T> vs template <class T>; both introduce a type parameter. typename is also needed for dependent type names inside templates.

Are templates compile-time or run-time polymorphism?

Compile-time (static) polymorphism – the right code is generated for each type before the program runs.

Why are templates defined in header files?

Because the compiler must see the whole definition to instantiate it for the types used in each source file.

Where can I learn more?

Read C++ Templates and C++20 Concepts, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links