liveBook · Manning

Template

As explained in Learn C++ by Example

A C++ template is a parameterized declaration from which the compiler can generate functions, classes, or other code for specified types or values.

A C++ template packages a reusable declaration around type or value parameters. Instead of writing separate classes for similar random distributions, one RandomBlob accepts a generator and distribution type, provided both support the operations its step function needs. section 6.2.1

Templates become useful when a small interface is shared by otherwise unrelated types:

  • Constrain parameters with concepts such as std::invocable when clearer diagnostics and an explicit callable interface matter. section 9.2.1

One class, several random behaviors

RandomBlob<T, U> derives from Blob, keeps a generator of type T and a distribution of type U, and advances with distribution(generator). Constructing it with uniform_int_distribution produces bounded steps; normal_distribution produces a different pattern. Supplying lambdas that return zero makes the behavior deterministic for a property check.

Listing 6.11 A general-purpose random blob
template <typename T, typename U>                          #1
class RandomBlob : public Blob
{
    int y = 0;
    T generator;                                           #1
    U distribution;                                        #1
public:
    RandomBlob(T gen, U dis)                               #1
        : generator(gen), distribution(dis)
    {
    }
    void step() override
    {
        y += static_cast<int>(distribution(generator));    #2
    }
    int total_steps() const override
    {
        return y;
    }
};

Inspect the complete RandomBlob listing to see template parameters, members, construction, invocation, and conversion working together. section 6.2.1

How Learn C++ by Example covers it

How deep it goes
Explains class and function templates through working examples, then adds concepts and constexpr, without descending into compilation internals.
Examples
Illustrates templates with RandomBlob, a slot-machine reel generator, and a mind-reading game.
What it assumes
Assumes basic classes, inheritance, constructors, callables, and random-library usage while demonstrating template syntax in context.
What you can do after
Apply templates via C++ class and function declarations, substitute compatible types, constrain callables, and replace randomness for tests.
How it connects
Connects templates with polymorphism, random distributions, lambdas, concepts, constexpr, and testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.