diff -r 3b279b5e57d3 -r fc1c13db9618 src/transform.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/transform.h Sun Feb 14 03:19:28 2016 +0200 @@ -0,0 +1,93 @@ +/* + * LDForge: LDraw parts authoring CAD + * Copyright (C) 2013 - 2016 Teemu Piippo + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once +#include + +// +// TransformingIterator +// +// Transforming iterator, calls Fn on iterated values before returning them. +// +template +struct TransformingIterator +{ + using Iterator = decltype(T().begin()); + using Self = TransformingIterator; + Iterator it; + std::function fn; + + TransformingIterator(Iterator it, std::function fn) : + it(it), + fn(fn) {} + + Res operator*() + { + return fn(*it); + } + + bool operator!= (const Self& other) const + { + return other.it != it; + } + + void operator++() + { + ++it; + } +}; + +// +// TransformWrapper +// +// Transform object, only serves to produce transforming iterators +// +template +struct TransformWrapper +{ + using Iterator = TransformingIterator; + + TransformWrapper(T& iterable, std::function fn) : + iterable(iterable), + function(fn) {} + + Iterator begin() + { + return Iterator(iterable.begin(), function); + } + + Iterator end() + { + return Iterator(iterable.end(), function); + } + + T& iterable; + std::function function; +}; + +template +TransformWrapper transform(T& iterable, Res(*fn)(Arg)) +{ + return TransformWrapper(iterable, fn); +} + +template +TransformWrapper transform(T& iterable, std::function fn) +{ + return TransformWrapper(iterable, fn); +}