Skip to content

Instantly share code, notes, and snippets.

@h-sigma
Created October 24, 2019 05:57
Show Gist options
  • Save h-sigma/3df46f087b8323ed9407a2c4d66f8584 to your computer and use it in GitHub Desktop.
Save h-sigma/3df46f087b8323ed9407a2c4d66f8584 to your computer and use it in GitHub Desktop.
Matches (possibly) enum values to function calls for patterns.
#include <vector>
#include <functional>
template<typename ENUM>
class PatternMatch
{
public:
PatternMatch() = default;
template<typename Func, ENUM ...Enums> void bindFunc(Func);
void match(ENUM);
template<ENUM e> void reset();
private:
std::vector<std::function<void(ENUM)>> mMappings;
};
template<typename ENUM>
void PatternMatch<ENUM>::match(ENUM e) {
for(auto& mapping : mMappings)
{
mapping(e);
}
}
template<typename ENUM>
template<ENUM e>
void PatternMatch<ENUM>::reset() {
for(auto& mapping : mMappings)
{
mapping(e);
}
}
template<typename ENUM>
template<typename Func, ENUM... Enums>
void PatternMatch<ENUM>::bindFunc(Func func) {
constexpr int count = sizeof...(Enums);
mMappings.push_back([count, func](ENUM val){
static ENUM pattern[count] {Enums...};
static int toBeMatched = 0;
toBeMatched = toBeMatched == count ? 0 : toBeMatched;
toBeMatched = val == pattern[toBeMatched] ? toBeMatched+1 : 0;
if(toBeMatched == count)
func();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment