Home > Article > Backend Development > When Would You Use Non-Type Parameters in C Templates?
Template with Non-Type Parameter
Template parameters are commonly used to specify type requirements, but it's also possible to declare templates with non-type parameters, such as unsigned integers.
Syntax and Meaning
The syntax for a template with a non-type parameter is:
template <unsigned int N>
where N represents the non-type parameter. This parameter can then be used within the template as a compile-time constant of type unsigned int.
Use Cases
Non-type parameters are useful in various scenarios:
Type Parameters vs. Non-Type Parameters
It's important to note the difference between type parameters and non-type parameters. Type parameters represent types (e.g., class T or template T), while non-type parameters represent constants (e.g., unsigned int N).
Example
Consider the following template:
template <unsigned int N>
struct Vector {
unsigned char bytes[N];
};
Here, N is a non-type parameter that determines the size of the bytes array.
<code class="cpp">Vector<3> v; // Vector with 3 bytes</code>
Default Values
It's possible to specify default values for non-type parameters, allowing the template to be used without explicitly providing the parameter. For instance:
<code class="cpp">template <unsigned int SIZE = 3> struct Vector { unsigned char buffer[SIZE]; };</code>
The above template defaults SIZE to 3, so the following is valid:
<code class="cpp">Vector v; // Equivalent to Vector<3></code>
Conclusion
Non-type parameters in templates offer flexibility and allow for code reuse with fixed or constant values. They enable a range of use cases, from array sizing to conditional compilation.
The above is the detailed content of When Would You Use Non-Type Parameters in C Templates?. For more information, please follow other related articles on the PHP Chinese website!