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
