Using template parameter values

The templates defined so far have had types as the parameters of the template, but you can also provide integer values. The following is a rather contrived example to illustrate the point:

    template<int size, typename T>     T* init(T t)     {         T* arr = new T[size];         for (int i = 0; i < size; ++i) arr[i] = t;         return arr;     }

There are two template parameters. The second parameter provides the name of a type where T is a placeholder used for the type of the parameter of the function. The first parameter looks like a function parameter because it is used in a similar way. The parameter size can be used in the function as a local (read-only) variable. The function parameter is T and so the compiler can deduce the second ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.