1

This is a commonly seen template function

template <typename T>
void func(T param) {
   // ...
}

However, I also see templates which look like this:

template <typename T, std::size_t N>  // note the extra N
void func(T param) {
   // ...
}

I know this is legal, but obvious N has nothing to do with parameters' type. What's the official rule here on adding an extra integer in the template? What is this called? Can I make the extra template param to be a float or double instead of integer? If not, why integer is special?

WhatABeautifulWorld
  • 3,198
  • 3
  • 22
  • 30
  • Possible duplicate of [Non-type template parameters](https://stackoverflow.com/questions/5687540/non-type-template-parameters) – user7860670 Jan 28 '18 at 19:10

1 Answers1

1

It's called non-type template parameters. You'r allowed to use simple types like integers

  • std::nullptr_t (since C++11);
  • integral type;
  • lvalue reference type (to object or to function);
  • pointer type (to object or to function);
  • pointer to member type (to member object or to member function);
  • enumeration type.

Note that since C++17 you can use auto to allow deduction of the non-type template parameter.

Floats and doubles are not allowed. But why?! Have a look at Why can't I use float value as a template parameter?

Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97
  • Could you give some example on non-type template using lvalue reference? This is really strange that works but float doesn't. I am more curious about the *why* part... – WhatABeautifulWorld Jan 29 '18 at 17:39