Thuta Learning
C++
AdvancedProgrammingBeginner

Templates & Concepts

C++Lesson 2735 min

What you'll walk away with

  • Write a function template and a class template and explain how the compiler instantiates them per type
  • Constrain a template with a standard concept such as std::integral or std::totally_ordered
  • Define your own concept with a requires expression and use it in the three common spellings
  • Read a constraint error and explain why template definitions belong in headers

Explain it simply

Templates and concepts in plain language

Imagine writing a max function for ints, then again for doubles, then again for strings. The bodies are identical; only the type changes. A template lets you write the body once with a type placeholder, and the compiler writes the int, double and string versions for you when you use them.

A concept is the label on that placeholder: 'any integer type' or 'anything you can print'. It turns the template's unspoken assumptions into a checked rule, so a wrong type is turned away at the door with a short message instead of failing deep inside the code.

Problem → Why → Solution

The problem: the error points at the wrong place

You write a template that doubles a number, and a teammate calls it with an std::string. The compiler accepts the call and only discovers the problem when it compiles the template body for strings. GCC reports the error at line 6, inside the body, and mentions the actual call only afterwards in a "required from here" note.

twice_string.cpp
#include <iostream>
#include <string>

template <typename T>
T twice(T value) {
    return value * 2;      // error: no match for 'operator*' (operand types are
}                          // 'std::__cxx11::basic_string<char>' and 'int')

int main() {
    std::string word = "hi";
    std::cout << twice(word) << '\n';   // the real mistake is here
}

Why the error looks like this

An unconstrained template accepts every type at the call and only discovers trouble when it compiles the body for that type. So the error talks about the template's internals (an operator* inside twice) instead of the real mistake (passing a string). Deep inside a library such as std::sort, the same kind of failure can produce a long chain of "required from" notes. A concept moves the check to the front door.

Core concept: code stamped out per type at compile time

Each time you call a function template such as template <typename T> T largest(T a, T b), the compiler works out T from the arguments (template argument deduction). It then instantiates a separate function for every distinct T. This happens at compile time, so there is no runtime cost, but each type gets its own copy of the code. When the arguments disagree, as in largest(3, 4.5), deduction fails and you name the type yourself: largest<double>(3, 4.5).

Classes can be templates too: std::vector<T> is one. You write template <typename T> class Counter { ... }; and use it as Counter<double>. Since C++17, class template argument deduction (CTAD) lets std::vector v{1, 2, 3} work out vector<int> on its own. Because instantiation happens where the template is used, the compiler must see the full definition there, which is why templates live in headers.

A C++20 concept is a named compile-time predicate on types. <concepts> provides std::integral, std::floating_point, std::same_as, std::convertible_to, std::totally_ordered and more. You write your own with a requires expression, which lists expressions that must compile; nothing in it is ever run. The constraint is checked at the call, before the body; if it is not satisfied, that overload is dropped and the error names the constraint that failed.

SpellingExample
Constrained parametertemplate <std::integral T> T twice(T v)
requires clausetemplate <typename T> requires std::integral<T>
Abbreviated templateauto twice(std::integral auto v)

When more than one constrained overload matches, the compiler prefers the one with the stricter constraint, so a generic version and a specialised one can live side by side. Remember that concepts check syntax only: a < b compiling does not mean it means what you hope. The body is still compiled against the real type, so the concept must cover every operation the body uses.

A template is a stencil, a concept its entry check
  1. Write the body once with a placeholder T
  2. Call site: the compiler deduces T
  3. Concept checks T before the body
  4. Compiler stamps out code for that T

Each distinct T gets its own compiled copy, so templates cost compile time and binary size, not run time.

General pattern

cpp
template <typename T>
T name(T a, T b) { /* ... */ }               // any T the body works for

template <std::integral T>                   // constrained by a standard concept
T name(T value) { /* ... */ }

template <typename T>
concept ConceptName = requires(T a) {        // your own concept
    a.method();                              // these expressions must compile
};

template <typename T> class Name { T member; };   // class template

template <...> declares the type parameters. Replacing typename with a concept name adds a constraint, and your own concepts are written with a requires expression.

Worked example: one standard concept, one of your own

twice accepts only integer types, while printAll accepts any vector whose element type can be printed with <<. The comments in main show what T is at each call. Uncomment the last line and the compiler rejects the double right at the call.

concepts.cpp
#include <concepts>
#include <iostream>
#include <string>
#include <vector>

template <std::integral T>                       // T must be an integer type
T twice(T value) {
    return value * 2;
}

template <typename T>
concept Printable = requires(std::ostream& os, const T& value) {
    os << value;                                 // this expression must compile
};

template <Printable T>
void printAll(const std::vector<T>& items) {
    for (const T& item : items) {
        std::cout << '[' << item << ']';
    }
    std::cout << '\n';
}

int main() {
    std::cout << twice(21) << '\n';              // T = int
    std::cout << twice(3'000'000'000LL) << '\n'; // T = long long
    printAll(std::vector<int>{1, 2, 3});         // T = int
    printAll(std::vector<std::string>{"tea", "rice"});  // T = std::string
    // twice(2.5);  // error: double does not satisfy std::integral
}

Code breakdown

  1. A constrained type parametertemplate <std::integral T>

    Writing std::integral instead of typename means the template is only usable when T is an integer type such as int, long long or char.

  2. Defining a conceptconcept Printable = requires(std::ostream& os, const T& value) {

    The requires expression declares test parameters os and value, and its body says os << value; must compile. The code is never run; the compiler only checks it.

  3. Using your own concepttemplate <Printable T>

    Your concept goes where typename was, exactly like a standard one. Both vector<int> and vector<std::string> qualify, so main can call printAll twice.

  4. Deduction picks long longtwice(3'000'000'000LL)

    The ' is a digit separator (since C++14) and LL makes the literal a long long, so T = long long and the result 6000000000, too big for an int, comes back correctly.

  5. The call that would fail// twice(2.5); // error: double does not satisfy std::integral

    Uncommented, GCC reports "no matching function for call to 'twice(double)'", then "constraints not satisfied" and "the expression 'is_integral_v<_Tp> [with _Tp = double]' evaluated to 'false'". The error points straight at the call in main.

You should see
42
6000000000
[1][2][3]
[tea][rice]

Three spellings, overloads and a class template

The program below uses all three ways of writing a constraint. The two describe overloads share a name but have different constraints, so the compiler picks the single one whose constraint the argument's type satisfies. Counter is a class that takes a type parameter.

template_forms.cpp
#include <concepts>
#include <iostream>

template <typename T>
    requires std::floating_point<T>              // requires clause
T half(T value) {
    return value / 2;
}

auto square(std::integral auto value) {          // abbreviated template
    return value * value;
}

void describe(std::integral auto) { std::cout << "integer\n"; }
void describe(std::floating_point auto) { std::cout << "floating point\n"; }

template <typename T>
class Counter {                                  // class template
public:
    void add(T amount) { total_ += amount; ++count_; }
    T total() const { return total_; }
    int count() const { return count_; }
private:
    T total_{};
    int count_ = 0;
};

int main() {
    std::cout << half(5.0) << '\n';
    std::cout << square(7) << '\n';
    describe(3);
    describe(2.5f);

    Counter<double> distance;                    // T = double, chosen explicitly
    distance.add(1.5);
    distance.add(2.25);
    std::cout << distance.count() << " runs, " << distance.total() << " km\n";
}

The output is 2.5, 49, integer, floating point and 2 runs, 3.75 km. In T total_{}, the {} value-initializes whatever T is, which is 0 for number types. Calling half(5) would not compile, because int is not a floating-point type; write half(5.0) or half<double>(5).

In real projects

Templates and concepts in real projects

You use templates daily before you write one: std::vector<T>, std::map<K, V>, std::unique_ptr<T> and every algorithm are templates. The C++20 std::ranges algorithms are constrained with concepts such as std::sortable, so trying std::ranges::sort on an std::list produces an error that names the unmet requirement. In your own code they pay off in places like these:

  • Containers and utilities: ring buffers, caches and statistics helpers are written once for many types, and a concept documents what they need from the element type.
  • Library APIs: a signature such as template <Serializable T> void save(const T&) tells callers which types are allowed without anyone reading the docs.
  • Strong types: a class template such as Money<Currency> stops you from adding dollars to euros at compile time instead of at run time.

Common mistakes

Common mistakes with templates and concepts

Putting the template definition in a .cpp file

With only a declaration in math.h and the body in math.cpp, main.cpp compiles but the linker reports "undefined reference to `int twice<int>(int)'". math.cpp never uses twice with int, so nobody instantiated that version. Put the whole template in the header.

Forgetting that std::integral accepts bool and char

twice(true) compiles and returns true, and -Wall warns "'*' in boolean context, suggest '&&' instead". Doubling a signed char holding 100 gives -56. If bool makes no sense, tighten the concept: std::integral<T> && !std::same_as<T, bool>.

A concept that does not cover what the body uses

Requiring only Printable while the body uses a < b means a type with << but no < fails with "no match for 'operator<'" from inside the body again. List every operation the body relies on, for example Printable<T> && std::totally_ordered<T>.

Expecting deduction to reconcile mixed argument types

largest(3, 4.5) fails with "deduced conflicting types for parameter 'T' ('int' and 'double')". Deduction does not apply conversions. Name the type, as in largest<double>(3, 4.5), or convert the argument yourself.

Best practices

Best practices

  • Add a constraint whenever a template does not truly work for every type; a bare typename promises 'anything'.
  • Look for a standard concept in <concepts> before writing your own; readers already know what the well-known ones mean.
  • Name concepts after a capability, such as Sortable or Printable, rather than after one piece of syntax like HasLessThan.
  • Template only the part that really varies by type; keeping the rest in ordinary functions saves compile time and binary size.

Mini challenge

Mini challenge: a Number concept and two generic helpers

Write a Number concept that accepts integer and floating-point types but rejects bool. Then write sumAll, which adds up a vector of Numbers, and largest, which finds the biggest element for any type that can be compared with <. For an empty vector, largest must be able to say 'no value'.

  • Build Number from std::integral, std::floating_point and std::same_as
  • Constrain sumAll with Number and start the total from T{}
  • Constrain largest with std::totally_ordered and return std::optional<T>
  • Call them with int, double and std::string vectors, and add one commented-out call that must not compile
generic_helpers.cpp
#include <concepts>
#include <iostream>
#include <optional>
#include <string>
#include <vector>

// TODO: concept Number = integer or floating point, but not bool

// TODO: constrain T with Number
template <typename T>
T sumAll(const std::vector<T>& values) {
    // TODO: start from T{} and add every value
}

// TODO: constrain T with std::totally_ordered
template <typename T>
std::optional<T> largest(const std::vector<T>& values) {
    // TODO: return std::nullopt for an empty vector, otherwise the biggest value
}

int main() {
    // TODO: test sumAll with ints and doubles, largest with ints and strings
    // TODO: show that largest of an empty vector has no value
}

Expected: It prints steps: 18800, prices: 7.75, largest step: 8100, largest name: Su (strings compare alphabetically) and empty has value: false. Uncommenting sumAll(names) gives a constraint error.

Show hint

The concept can be written as (std::integral<T> || std::floating_point<T>) && !std::same_as<T, bool>. std::optional<T> is a box that may or may not hold a value: std::nullopt means empty, and the caller uses has_value() and value() to check and unpack it.

Show solution
generic_helpers.cpp
#include <concepts>
#include <iostream>
#include <optional>
#include <string>
#include <vector>

template <typename T>
concept Number = (std::integral<T> || std::floating_point<T>) && !std::same_as<T, bool>;

template <Number T>
T sumAll(const std::vector<T>& values) {
    T total{};                                   // 0 for every number type
    for (const T& v : values) total += v;
    return total;
}

template <std::totally_ordered T>
std::optional<T> largest(const std::vector<T>& values) {
    if (values.empty()) return std::nullopt;     // no largest in an empty list
    T best = values.front();
    for (const T& v : values) {
        if (best < v) best = v;
    }
    return best;
}

int main() {
    std::vector<int> steps{4200, 8100, 6500};
    std::vector<double> prices{2.5, 4.25, 1.0};
    std::vector<std::string> names{"Su", "Aye", "Ko"};

    std::cout << "steps: " << sumAll(steps) << '\n';
    std::cout << "prices: " << sumAll(prices) << '\n';
    std::cout << "largest step: " << largest(steps).value() << '\n';
    std::cout << "largest name: " << largest(names).value() << '\n';
    std::cout << "empty has value: " << std::boolalpha
              << largest(std::vector<int>{}).has_value() << '\n';
    // sumAll(names);  // error: std::string does not satisfy Number
}

Quick quiz 1 / 3

Given template <std::integral T> T twice(T v) { return v * 2; }, which call compiles?

Quick quiz 2 / 3

twice is declared in math.h and defined in math.cpp. main.cpp calls twice(21) and the build fails with "undefined reference to `int twice<int>(int)'". Why?

Quick quiz 3 / 3

Which concept accepts int and double but rejects bool and std::string? (std:: omitted)

What to remember

  • A template lets you write the body once; the compiler generates code for each T you use, at compile time.
  • T is deduced from the arguments without conversions, so name it yourself, as in largest<double>(...), when they disagree.
  • A concept checks the type at the call and gives a short error naming the requirement that failed.
  • A requires expression only checks that expressions compile; make it cover every operation the body uses.
  • Keep template definitions in headers, or the linker reports an undefined reference.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Templates & Concepts | Thuta Learning