From 0b43d984905f07c59e3236d98d4e27409aba3cda Mon Sep 17 00:00:00 2001 From: Sebastiano Tronto Date: Fri, 17 Jan 2025 16:23:24 +0100 Subject: More stuff with templates --- templates/factorial.cpp | 22 ++++++++++++++++++++++ templates/println.cpp | 18 ++++++++++++++++++ templates/std_array.cpp | 16 ++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 templates/factorial.cpp create mode 100644 templates/println.cpp create mode 100644 templates/std_array.cpp (limited to 'templates') diff --git a/templates/factorial.cpp b/templates/factorial.cpp new file mode 100644 index 0000000..11e4789 --- /dev/null +++ b/templates/factorial.cpp @@ -0,0 +1,22 @@ +// Taken from https://en.wikipedia.org/wiki/Template_metaprogramming + +#include + +template +class factorial { +public: + static constexpr long long value = N * factorial::value; +}; + +template<> +class factorial<0> { +public: + static constexpr long long value = 1; +}; + +int main() { + constexpr long long X = 12; + std::cout << factorial::value << std::endl; + + return 0; +} diff --git a/templates/println.cpp b/templates/println.cpp new file mode 100644 index 0000000..62f27ac --- /dev/null +++ b/templates/println.cpp @@ -0,0 +1,18 @@ +#include + +template void println() { std::cout << X << std::endl; } + +int main() { + println<1.23>(); + println<42>(); + + // The following attempts to print a string do not work + // uncomment to see why + // 1. + // println<"Hello!">(); + // 2. + // constexpr std::string_view hello = "Hello!"; + // println(); + + return 0; +} diff --git a/templates/std_array.cpp b/templates/std_array.cpp new file mode 100644 index 0000000..8044cb2 --- /dev/null +++ b/templates/std_array.cpp @@ -0,0 +1,16 @@ +#include +#include + +int main() { + std::array a {1.0, 1.1, 1.2}; + std::cout << "Capacity of a: " << a.size() << std::endl; + + a[3] = 1.3; + a[4] = 1.4; + + for (auto x : a) + std::cout << x << " "; + std::cout << std::endl; + + return 0; +} -- cgit v1.3