taming-cpp

Experiments with C++ and comparisons with C
git clone https://git.tronto.net/taming-cpp
Download | Log | Files | Refs | README

commit 0b43d984905f07c59e3236d98d4e27409aba3cda
parent d0f3f64bb42ea8194c20f0eadd35821cab346143
Author: Sebastiano Tronto <sebastiano@tronto.net>
Date:   Fri, 17 Jan 2025 16:23:24 +0100

More stuff with templates

Diffstat:
Atemplates/factorial.cpp | 22++++++++++++++++++++++
Atemplates/println.cpp | 18++++++++++++++++++
Atemplates/std_array.cpp | 16++++++++++++++++
3 files changed, 56 insertions(+), 0 deletions(-)

diff --git a/templates/factorial.cpp b/templates/factorial.cpp @@ -0,0 +1,22 @@ +// Taken from https://en.wikipedia.org/wiki/Template_metaprogramming + +#include <iostream> + +template<long long N> +class factorial { +public: + static constexpr long long value = N * factorial<N-1>::value; +}; + +template<> +class factorial<0> { +public: + static constexpr long long value = 1; +}; + +int main() { + constexpr long long X = 12; + std::cout << factorial<X>::value << std::endl; + + return 0; +} diff --git a/templates/println.cpp b/templates/println.cpp @@ -0,0 +1,18 @@ +#include <iostream> + +template<auto X> 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<hello>(); + + return 0; +} diff --git a/templates/std_array.cpp b/templates/std_array.cpp @@ -0,0 +1,16 @@ +#include <array> +#include <iostream> + +int main() { + std::array<double, 5> 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; +}