Skip to content

Commit 53fa3e5

Browse files
committed
add some examples
1 parent 0d18ccb commit 53fa3e5

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

README.md

+3
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,9 @@ The primary use-case for this is on-the-fly RAII-like resource management for ty
6464
Usage examples can be found [here](examples/examples_defer.cpp).
6565

6666

67+
### `tuple algorthims`
68+
Some algorithms for iterating tuples, for example `tuple_fold` a fold/reduce implementation for tuples.
69+
6770
### Further Examples
6871

6972
Compilable code examples can be found in [examples](./examples). The example build requires the cmake

examples/CMakeLists.txt

+7
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,11 @@ add_executable(examples_defer
4343
target_link_libraries(examples_defer
4444
PRIVATE
4545
dice-template-library::dice-template-library
46+
)
47+
48+
add_executable(examples_tuple_algorithm
49+
examples_tuple_algorithm.cpp)
50+
target_link_libraries(examples_tuple_algorithm
51+
PRIVATE
52+
dice-template-library::dice-template-library
4653
)

examples/examples_tuple_algorithm.cpp

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include <dice/template-library/tuple_algorithm.hpp>
2+
3+
#include <cassert>
4+
#include <iostream>
5+
#include <limits>
6+
#include <tuple>
7+
8+
void tuple_fold() {
9+
std::tuple<int, double, float, long> tup{5, 1.2, 1.3F, 1L};
10+
11+
auto const sum = dice::template_library::tuple_fold(tup, 0L, [](auto acc, auto x) {
12+
return acc + static_cast<long>(x);
13+
});
14+
15+
assert(sum == 8);
16+
}
17+
18+
void tuple_type_fold() {
19+
using tuple_t = std::tuple<int, long>;
20+
21+
auto const digits_sum = dice::template_library::tuple_type_fold<tuple_t>(0UL, []<typename T>(auto acc) {
22+
return acc + std::numeric_limits<T>::digits10;
23+
});
24+
25+
assert(digits_sum == 27);
26+
}
27+
28+
void tuple_for_each() {
29+
std::tuple<int, double, float> tup{1, 1.0, 1.0F};
30+
31+
dice::template_library::tuple_for_each(tup, [](auto &x) {
32+
x += 1;
33+
});
34+
35+
assert((tup == std::tuple<int, double, float>{2, 2.0, 2.0F}));
36+
}
37+
38+
void tuple_type_for_each() {
39+
using tuple_t = std::tuple<int, double, float>;
40+
41+
dice::template_library::tuple_type_for_each<tuple_t>([&]<typename T>() {
42+
std::cout << typeid(T).name() << '\n';
43+
});
44+
}
45+
46+
int main() {
47+
tuple_fold();
48+
tuple_type_fold();
49+
tuple_for_each();
50+
tuple_type_for_each();
51+
}

0 commit comments

Comments
 (0)