Templates
Non-Type Templates
Templates can also take small compile-time values, such as an array size.
Non-Type Templates
non_type_templates.cpp
#include <array>
#include <iostream>
template <int Size>
int fillAndSum(int start) {
std::array<int, Size> values{};
int total = 0;
for (int index = 0; index < Size; index++) {
values[index] = start + index;
total += values[index];
}
return total;
}
int main() {
int start = ;
int total = fillAndSum<3>(start);
std::cout << "size=3" << std::endl;
std::cout << "start=" << start << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <array>
#include <iostream>
template <int Size>
int fillAndSum(int start) {
std::array<int, Size> values{};
int total = 0;
for (int index = 0; index < Size; index++) {
values[index] = start + index;
total += values[index];
}
return total;
}
int main() {
int start = ;
int total = fillAndSum<3>(start);
std::cout << "size=3" << std::endl;
std::cout << "start=" << start << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <array>
#include <iostream>
template <int Size>
int fillAndSum(int start) {
std::array<int, Size> values{};
int total = 0;
for (int index = 0; index < Size; index++) {
values[index] = start + index;
total += values[index];
}
return total;
}
int main() {
int start = ;
int total = fillAndSum<3>(start);
std::cout << "size=3" << std::endl;
std::cout << "start=" << start << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
non-type parameter
A non-type template parameter is a value known at compile time, like the `Size` in `std::array<int, Size>`.