Using integers as template parameters

Beyond general types, a template can also be of any integral type, which means that the compiler generates a new function for every integer passed as the template argument:

template <int N, typename T> 
auto const_pow_n(const T& v) { 
  auto product = T{1}; 
  for(int i = 0; i < N; ++i) {     product *= v;   }
  return product; 
}// The compiler generates a function which squares the valueauto x2 = const_pow_n<float, 2>(4.0f); // The compiler generates a function which cubes the valueauto x3 = const_pow_n<float, 3>(4.0f);

Note the difference between the template parameter N and the function parameter v. For every value of N, the compiler generates a new function. However, v is passed as a regular parameter and, as ...

Get C++ High Performance 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.