Creating complex predicates with logical conjunction
When filtering data with generic code, we end up defining predicates, which tell what data we want, and what data we do not want. Sometimes predicates are the combinations of different predicates.
When filtering strings, for example, we could implement a predicate that returns true
if its input string begins with "foo"
. Another predicate could return true if its input string ends with "bar"
.
Instead of writing custom predicates all the time, we can reuse predicates by combining them. If we want to filter strings that begin with "foo"
and end with "bar"
, we can just pick our existing predicates and combine them with a logical and. In this section, we play with lambda expressions in order to find a comfortable way to do this.
How to do it...
We will implement very simple string filter predicates, and then we will combine them with a little helper function that does the combination for us in a generic way.
- As always, we'll include some headers...