Non-type template parameter
suggest changeApart from type template parameters, a template can take non-type parameters. Through C++17, such a parameter has one of these types:
- an integral or enumeration type,
- a pointer to object or pointer to function,
- an lvalue reference to object or lvalue reference to function,
- a pointer to member,
std::nullptr_t(since C++11).
C++20 adds further types, including floating-point types and certain class types.
Like all template parameters, non-type template parameters can be explicitly specified, defaulted, or derived implicitly via Template Argument Deduction.
Example of non-type template parameter usage:
#include <iostream>
template<typename T, std::size_t size>
std::size_t size_of(T (&anArray)[size]) // Pass the array by reference so the
{ // parameter has an exact size. The
return size; // template parameter accepts any size.
}
int main()
{
char anArrayOfChar[15];
std::cout << "anArrayOfChar: " << size_of(anArrayOfChar) << "\n";
int anArrayOfData[] = {1,2,3,4,5,6,7,8,9};
std::cout << "anArrayOfData: " << size_of(anArrayOfData) << "\n";
}
Example of explicitly specifying both type and non-type template parameters:
#include <array>
int main ()
{
std::array<int, 5> foo; // int is a type parameter, 5 is non-type
}
Non-type template parameters are one way to write recursive templates and other metaprogramming.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents