Pattern Matching

Get familiar with pattern matching that may become a part of C++23.

New data types such as std::tuple or std::variant need new ways to work with their elements. Simple if or switch conditions or functions like std::apply or std::visit can only provide basic functionality. Pattern matching, heavily used in functional programming, enables the more powerful handling of the new data types.

The following code snippets from the proposal P1371R2 on pattern matching compare classical control structures with pattern matching. Pattern matching uses the keyword inspect and __ for a placeholder.

  • switch statement

    The following snippet is an example of a switch statement versus pattern matching.

    switch (x) {
        case 0: std::cout << "got zero"; break;
        case 1: std::cout << "got one"; break;
        default: std::cout << "don't care";
    }
    
    inspect (x) {
        0: std::cout << "got zero";
        1: std::cout << "got one";
        __: std::cout << "don't care";
    }
    

Get hands-on with 1200+ tech skills courses.