Instantiation

Template declarations and specializations describe the form that a class or function can take but do not create any actual classes or functions. To do these things, you must instantiate a template.

Most often, you implicitly instantiate a template by using it in a function call, object declaration, or similar context. The template instance requires a template argument for each template parameter. The arguments can be explicit (enclosed in angle brackets and separated by commas) or implicit (default arguments for class templates or deduced arguments for function templates):

template<typename T> T plus(T a, T b) { return a + b; }
template<typename T = int> struct wrapper {
  T value;
};
int x = plus(10, 20); // Instantiate plus<int>.
wrapper<double> x;    // Instantiate wrapper<double>.
wrapper<> w;            // Instantiate wrapper<int>.

A class member expression (. or -> operator) that names an instance of a member function template with template arguments must use the template keyword before the member name. Similarly, a qualified name of a member template must use template before the member name. Otherwise, the < symbol that introduces the template argument list is interpreted as the less-than operator:

class bigfloat {
  template<unsigned N> double round(  );
  template<unsigned N> static double round(double);
};

bigfloat f;
std::cout << f.template round<2>(  ) << '\n';
std::cout << bigfloat::template round<8>(PI) << '\n';

Instantiating a class template does not necessarily instantiate all ...

Get C++ In a Nutshell 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.