std::variant and the Power of Pattern Matching

Speaker: Nikolai Wuttke

Audience level: Beginner | Intermediate

category

C++17 introduced std::variant, a so called “sum type”: a class that can, at one point in time, hold an object of one type out of a set of possible alternatives. On the surface, it’s a fairly simple concept, but it also enables a powerful new programming style: pattern matching. Originally coming from functional programming languages, pattern matching allows for very clear and straightforward code for a variety of use cases. While not being a first class language feature in C++, we can emulate it fairly well by using std::variant and adding a bit of utility code to implement a match function. This is possible even in C++11 by using libraries to provide a variant implementation.

In this talk, I’m first going to show how pattern matching works in general and how it compares to other approaches. Next, I'll give an overview on how to integrate it into code bases with different C++ standards (11, 14, 17). Afterwards, I will present detailed examples for the following three use cases:

<ol>
  • State machine for a 2D game “AI”
  • Event handling system for a GUI application
  • Interpreter for a scripting language
  • </ol>

    For each example, I will evaluate the resulting code in comparison to other approaches in terms of performance and clarity/maintainability. Finally, the talk will finish with a recommendation on when to use this approach.