src/transform.h

changeset 1319
39d7a9642eea
parent 1318
568fcfc6da71
child 1320
bdb4804bc09c
equal deleted inserted replaced
1318:568fcfc6da71 1319:39d7a9642eea
1 /*
2 * LDForge: LDraw parts authoring CAD
3 * Copyright (C) 2013 - 2017 Teemu Piippo
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #pragma once
20 #include <functional>
21
22 //
23 // TransformingIterator
24 //
25 // Transforming iterator, calls Fn on iterated values before returning them.
26 //
27 template<typename T, typename Res, typename Arg>
28 struct TransformingIterator
29 {
30 using Iterator = decltype(T().begin());
31 using Self = TransformingIterator<T, Res, Arg>;
32 Iterator it;
33 std::function<Res(Arg)> fn;
34
35 TransformingIterator(Iterator it, std::function<Res(Arg)> fn) :
36 it(it),
37 fn(fn) {}
38
39 Res operator*()
40 {
41 return fn(*it);
42 }
43
44 bool operator!= (const Self& other) const
45 {
46 return other.it != it;
47 }
48
49 void operator++()
50 {
51 ++it;
52 }
53 };
54
55 //
56 // TransformWrapper
57 //
58 // Transform object, only serves to produce transforming iterators
59 //
60 template<typename T, typename Res, typename Arg>
61 struct TransformWrapper
62 {
63 using Iterator = TransformingIterator<T, Res, Arg>;
64
65 TransformWrapper(T& iterable, std::function<Res(Arg)> fn) :
66 iterable(iterable),
67 function(fn) {}
68
69 Iterator begin()
70 {
71 return Iterator(iterable.begin(), function);
72 }
73
74 Iterator end()
75 {
76 return Iterator(iterable.end(), function);
77 }
78
79 T& iterable;
80 std::function<Res(Arg)> function;
81 };
82
83 template<typename T, typename Res, typename Arg>
84 TransformWrapper<T, Res, Arg> transform(T& iterable, Res(*fn)(Arg))
85 {
86 return TransformWrapper<T, Res, Arg>(iterable, fn);
87 }
88
89 template<typename T, typename Res, typename Arg>
90 TransformWrapper<T, Res, Arg> transform(T& iterable, std::function<Res(Arg)> fn)
91 {
92 return TransformWrapper<T, Res, Arg>(iterable, fn);
93 }

mercurial