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:
std::size_t Size = 5
.FixedVector<int>
will use the default size of 5.FixedVector<double, 3>
creates a vector with a capacity of 3.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.
Answers to questions are automatically generated and may not have been reviewed.
Learn how templates can be used to create multiple classes from a single blueprint