Created
December 17, 2015 13:51
-
-
Save alepez/696e3bcf18e869c53750 to your computer and use it in GitHub Desktop.
c++11 checker composition
This file contains hidden or 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
| template <typename T> | |
| using Checker = std::function<bool(T)>; | |
| template <typename T> | |
| class Param { | |
| public: | |
| Param(std::string, Checker<T>) { | |
| } | |
| Param(std::string) { | |
| } | |
| }; | |
| class Regex { | |
| public: | |
| Regex(std::string regex) | |
| : regex_{regex} { | |
| } | |
| bool operator()(std::string) { | |
| return true; | |
| } | |
| private: | |
| const std::string regex_; | |
| }; | |
| template <typename T> | |
| class All { | |
| public: | |
| All(); | |
| }; | |
| template <typename T> | |
| class Max { | |
| public: | |
| Max(T max) | |
| : max_{max} { | |
| } | |
| bool operator()(T value) { | |
| return value < max_; | |
| } | |
| private: | |
| const T max_; | |
| }; | |
| template <typename T> | |
| class Min { | |
| public: | |
| Min(T min) | |
| : min_{min} { | |
| } | |
| bool operator()(T value) { | |
| return value > min_; | |
| } | |
| private: | |
| const T min_; | |
| }; | |
| template <typename T> | |
| Checker<T> operator+(Checker<T> l, Checker<T> r) { | |
| return [l, r](T value) { | |
| return l(value) && r(value); | |
| }; | |
| } | |
| template <typename T> | |
| Checker<T> all(Checker<T> l, Checker<T> r) { | |
| return [l, r](T value) { | |
| return l(value) && r(value); | |
| }; | |
| } | |
| TEST(XXX, YYY) { | |
| /* senza checker */ | |
| Param<std::string>("ciao"); | |
| /* con lambda */ | |
| auto checker = [](std::string toBeChecked) { return toBeChecked == "foo"; }; | |
| Param<std::string>("ciao", checker); | |
| /* con callable */ | |
| Param<std::string>("ciao", Regex(".*")); | |
| Param<int>("foo.bar", all<int>(Min<int>(5), Max<int>(9))); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment