Templates
Non-Type Templates
Templates can also take small compile-time values, such as an array size.
non-type parameter
A non-type template parameter is a value known at compile time, like the `Size` in `std::array<int, Size>`.
Non-Type Templates
non_type_templates.cpp
Replay: real traced execution (multi-file project)
#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 = 4;
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 = 1;
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 = 10;
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;
}
start ← 4, total ← 15
17int main() {18 int start→ 4 = 4; //@start=1, 101920 int total→ 15 = fillAndSum<3>(start4);2122 std::cout << "size=3" << std::endl;23 std::cout << "start=" << start4 << std::endl;24 std::cout << "total=" << total15 << std::endl;25 return 0;26}outputsize=3 start=4 total=15
start ← 1, total ← 6
17int main() {18 int start→ 1 = 1;1920 int total→ 6 = fillAndSum<3>(start1);2122 std::cout << "size=3" << std::endl;23 std::cout << "start=" << start1 << std::endl;24 std::cout << "total=" << total6 << std::endl;25 return 0;26}outputsize=3 start=1 total=6
start ← 10, total ← 33
17int main() {18 int start→ 10 = 10;1920 int total→ 33 = fillAndSum<3>(start10);2122 std::cout << "size=3" << std::endl;23 std::cout << "start=" << start10 << std::endl;24 std::cout << "total=" << total33 << std::endl;25 return 0;26}outputsize=3 start=10 total=33