Pattern matching in C++14

EventHelix
Software Design
Published in
2 min readJun 24, 2017

Pattern matching in C++ is an alternative to using if statements to control the logic flow. Pattern matching lets you organize the code as matching patterns and the statements to be executed when the pattern match is found.

You can think of pattern matching as a generalization of the switch-case statement in C and C++.

The following example of computing factorial uses pattern matching to implement the factorial of a number. This is achieved by matching two patterns in the specified order:

  • Pattern 0 → 1
  • Pattern n → n * factorial (n-1)
int factorial(int n) {
using namespace mpark;
return match(n)(
pattern(0) = [] {return 1;},
pattern(arg) = [](auto n) {return n*factorial(n-1);}
);

}

You can use more complex pattern matches. The example given below illustrates a pattern match based on two numbers. The pattern specified here is matching two numbers. The pattern conditions for matching are specified as:

  • Pattern (i is divisible by 3, i is divisible by 5) → “fizzbzz”
  • Pattern (i is divisible by 3, i is not divisible by 5) → “fizz”
  • Pattern (i is not divisible by 3, i is divisible by 5) → “buzz”
  • Pattern (i is not divisible by 3 or 5) → i

The pattern matching code for this example is:

void fizzbuzz() {
for (int i = 1; i <= 100; ++i) {
using namespace mpark;
match(i % 3, i % 5)(
pattern(0, 0) = [] { std::cout << "fizzbuzz\n"; },
pattern(0, _) = [] { std::cout << "fizz\n"; },
pattern(_, 0) = [] { std::cout << "buzz\n"; },
pattern(_, _) = [i] { std::cout << i << std::endl; }
);

}
}

We have scratched the surface of what you can do with Michael Park’s pattern matching library on GitHub. The following video at @cppnow further illustrates the use of the patterns library.

Pattern matching in C++ 14

--

--