Default Values for Non-Type Template Parameters
Is it possible to have default values for non-type template parameters?
Yes, it is indeed possible to have default values for non-type template parameters in C++. This feature allows you to provide a default value that will be used if the user doesn't specify a value when instantiating the template. It works similarly to default function arguments.
Here's an example demonstrating how to use default values for non-type template parameters:
#include <array>
#include <iostream>
// Template with a non-type parameter
// with a default value
template <typename T, std::size_t Size = 5>
class FixedVector {
private:
std::array<T, Size> data;
std::size_t count{0};
public:
void Add(const T& value) {
if (count < Size) {
data[count++] = value;
}
}
void Print() const {
for (std::size_t i = 0; i < count; ++i) {
std::cout << data[i] << ' ';
}
std::cout << '\n';
}
std::size_t Capacity() const { return Size; }
};
int main() {
// Using default size
FixedVector<int> vec1;
vec1.Add(1);
vec1.Add(2);
vec1.Add(3);
std::cout << "Vec1 (default size): ";
vec1.Print();
std::cout << "Capacity: "
<< vec1.Capacity() << '\n';
// Specifying a custom size
FixedVector<double, 3> vec2;
vec2.Add(1.1);
vec2.Add(2.2);
vec2.Add(3.3);
// This won't be added as it exceeds capacity
vec2.Add(4.4);
std::cout << "Vec2 (custom size): ";
vec2.Print();
std::cout << "Capacity: "
<< vec2.Capacity() << '\n';
}
Vec1 (default size): 1 2 3
Capacity: 5
Vec2 (custom size): 1.1 2.2 3.3
Capacity: 3
In this example, we've created a FixedVector
class template that uses a non-type template parameter Size
to determine the capacity of the vector. We've given Size
a default value of 5.
Key points to note:
- The syntax for providing a default value is similar to function default arguments:
std::size_t Size = 5
. - When instantiating the template, you can omit the non-type argument if you're happy with the default value:
FixedVector<int>
will use the default size of 5. - You can still specify a custom value if needed:
FixedVector<double, 3>
creates a vector with a capacity of 3. - Default values for template parameters must be constant expressions that can be evaluated at compile-time.
- You can have multiple non-type template parameters with default values, just like function arguments.
Default values for non-type template parameters can make your templates more flexible and easier to use, as they allow users to opt for a sensible default behavior while still providing the option to customize when needed.
Remember that once you provide a default value for a template parameter, all subsequent parameters must also have default values. This is similar to the rule for function default arguments.
Class Templates
Learn how templates can be used to create multiple classes from a single blueprint