Created
June 3, 2014 09:52
-
-
Save TheBurnDoc/037488c548f14d1aefd8 to your computer and use it in GitHub Desktop.
A simple Pipeline template example, with Sequence and Filter implementations - Sequence simply chains together functions to be executed sequentially and Filter can be used to erase the contents of a standard container based on staged rule functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pipeline base class | |
template <typename T, typename F> | |
class Pipeline | |
{ | |
public: | |
typedef std::function<F> Func; | |
Pipeline() = default; | |
Pipeline(std::list<Func> stages) : _stages(stages) {} | |
void addStage(Func func) { _stages.push_back(func); } | |
void clearStages() { _stages.clear(); } | |
// Madated process function | |
virtual T process(T val) = 0; | |
protected: | |
std::list<Func> _stages; | |
}; | |
// Sequence is a pipeline that simply chains functions together | |
template <typename T> | |
class Sequence : public Pipeline<T, T(T)> | |
{ | |
public: | |
Sequence() = default; | |
Sequence(std::list<Func> stages) : Pipeline(stages) {} | |
T process(T val) | |
{ | |
for (auto& func : _funcs) | |
val = func(std::move(val)); | |
return val; | |
} | |
}; | |
// Filter is a pipeline that reduces the items in a collection | |
template <typename T, typename C> | |
class Filter : public Pipeline<C, bool(T)> | |
{ | |
public: | |
Filter() = default; | |
Filter(std::list<Func> stages) : Pipeline(stages) {} | |
C process(C val) | |
{ | |
// Convert container to list for fastest erasing | |
std::list<T> eraser = { val.begin(), val.end() }; | |
// For each item in container (val) | |
bool erased; | |
for (auto itr = eraser.begin(); itr != eraser.end(); ) | |
{ | |
erased = false; | |
// For each filter function (_funcs) | |
for (auto& func : _stages) | |
{ | |
// If filter function returns false erase | |
if (!func(*itr)) | |
{ | |
itr = eraser.erase(itr); | |
erased = true; | |
break; | |
} | |
} | |
// Iterate | |
if (!erased) ++itr; | |
} | |
// Convert list back to U on exit | |
return { eraser.begin(), eraser.end() }; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment