Patternia is a header-only pattern matching library for modern C++. It keeps matching expression-oriented, explicit, and zero-overhead.
#include <ptn/patternia.hpp>
int classify(int x) {
using namespace ptn;
return match(x) | on(
lit(0) >> 0,
lit(1) >> 1,
_ >> -1
);
}match(subject) creates the evaluation context.
on(...) provides the ordered case list.
pattern >> handler defines one case.
_ is the required fallback case.
- Literal, structural, and
std::variantmatching in one DSL. - Explicit binding through
$and$(...). - Declarative guards via
PTN_LET,PTN_WHERE,_0,arg<N>,rng(...), and callables. - No RTTI, no virtual dispatch, no heap allocation.
- Static literal and variant dispatch lowering for hot paths.
using namespace ptn;
const char *bucket(int x) {
return match(x) | on(
$[PTN_LET(value, value < 0)] >> "negative",
$[PTN_LET(value, value < 10)] >> "small",
_ >> "large"
);
}using namespace ptn;
struct Point { int x; int y; };
int magnitude2(const Point &p) {
return match(p) | on(
$(has<&Point::x, &Point::y>()) >> [](int x, int y) {
return x * x + y * y;
},
_ >> 0
);
}using namespace ptn;
using Value = std::variant<int, std::string>;
std::string describe(const Value &v) {
return match(v) | on(
is<int>() >> "int",
$(is<std::string>()) >> [](const std::string &s) {
return "str:" + s;
},
_ >> [] { return std::string("other"); }
);
}Patternia is header-only with no external dependencies.
FetchContent (recommended):
include(FetchContent)
FetchContent_Declare(patternia
GIT_REPOSITORY https://github.com/sentomk/patternia.git
GIT_TAG v0.9.0
)
FetchContent_MakeAvailable(patternia)
target_link_libraries(your_target PRIVATE patternia::patternia)Direct clone:
git clone https://github.com/SentoMK/patternia.git
cd patternia
cmake -S . -B build
cmake --build buildSee Installation Guide for find_package, submodule, and header-copy options.
cmake -S . -B build -DPTN_BUILD_TESTS=ON
cmake --build build --target ptn_tests
ctest --test-dir build --output-on-failureCache the case pack for repeated hot paths:
using namespace ptn;
int fast_classify(int x) {
return match(x) | PTN_ON(
lit<1>() >> 1,
lit<2>() >> 2,
_ >> 0
);
}PTN_ON(...) is a convenience wrapper over static_on(...).
It avoids rebuilding the matcher object on every call.
Please read CONTRIBUTING.md before sending changes. This project is governed by CODE_OF_CONDUCT.md.