Non-type template parameter

suggest change

Apart from type template parameters, a template can take non-type parameters. Through C++17, such a parameter has one of these types:

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents