Building Better State Machines in Modern C++: CXXStateTree
State machines are the backbone of countless software systems - from game AI and UI flows to embedded devices and network protocols. Yet, implementing them in C++ often feels like weโre stuck in the past: endless switch statements, tangled conditionals, and boilerplate that makes your eyes glaze over.
What if there was a better way?
๐ Meet CXXStateTree
CXXStateTree is a modern, header-only C++20 library that brings elegance and performance to state machine development. Itโs designed for developers who want clean, maintainable code without sacrificing the performance C++ is known for.
๐ก Why Another State Machine Library?
Fair question! Hereโs what makes CXXSโฆ
Building Better State Machines in Modern C++: CXXStateTree
State machines are the backbone of countless software systems - from game AI and UI flows to embedded devices and network protocols. Yet, implementing them in C++ often feels like weโre stuck in the past: endless switch statements, tangled conditionals, and boilerplate that makes your eyes glaze over.
What if there was a better way?
๐ Meet CXXStateTree
CXXStateTree is a modern, header-only C++20 library that brings elegance and performance to state machine development. Itโs designed for developers who want clean, maintainable code without sacrificing the performance C++ is known for.
๐ก Why Another State Machine Library?
Fair question! Hereโs what makes CXXStateTree different:
โก Zero Heap Allocation
Every allocation counts in performance-critical applications. CXXStateTree is designed with a zero-allocation philosophy - everything stays on the stack where possible.
๐ง Fluent Builder API
No more fighting with complex constructors or configuration objects. Build your state machine the way youโd draw it on a whiteboard:
#include <iostream>
#include "CXXStateTree/StateTree.hpp"
using namespace CXXStateTree;
int main() {
auto machine = StateTree::Builder()
.initial("Idle")
.state("Idle", [](State& s) {
s.on("Start", "Running", nullptr, []() {
std::cout << "๐ Starting engine..." << std::endl;
});
})
.state("Running", [](State& s) {
s.on("Stop", "Idle", nullptr, []() {
std::cout << "๐ Stopping engine..." << std::endl;
});
})
.build();
machine.send("Start"); // Output: ๐ Starting engine...
machine.send("Stop"); // Output: ๐ Stopping engine...
}
Clean. Readable. Self-documenting.
๐ก๏ธ Guards and Actions
Real-world state machines need conditional logic. CXXStateTree lets you attach guards (conditions) and actions to transitions:
auto doorMachine = StateTree::Builder()
.initial("Closed")
.state("Closed", [](State& s) {
s.on("Open", "Open",
[]() {
// Guard: only open if unlocked
return !isDoorLocked();
},
[]() {
// Action: perform the opening
std::cout << "๐ช Opening door..." << std::endl;
}
);
})
.state("Open", [](State& s) {
s.on("Close", "Closed", nullptr, []() {
std::cout << "๐ช Closing door..." << std::endl;
});
})
.build();
๐ณ Hierarchical States (Available!)
One of the most powerful features - nested states for modeling complex behaviors:
Game Character
โโโ Alive
โ โโโ Idle
โ โโโ Walking
โ โโโ Running
โโโ Dead
This allows you to handle events at different levels of specificity, reducing code duplication and improving maintainability.
๐ฏ Real-World Use Cases
CXXStateTree shines in:
- ๐ฎ Game Development: Character AI, game flow, animation controllers
- ๐ฑ UI Development: Form wizards, navigation flows, modal states
- ๐ค Embedded Systems: Protocol handlers, device state management
- ๐ Network Programming: Connection state machines, protocol implementations
- ๐ฆพ Robotics: Behavior trees, task scheduling
๐ฆ Getting Started
Requirements
- C++20 compiler (GCC โฅ 10, Clang โฅ 11, MSVC โฅ 2019)
- CMake (for building)
Installation
Option 1: Single Header (Recommended)
git clone https://github.com/ZigRazor/CXXStateTree.git
cd CXXStateTree
cmake -S . -B build -DENABLE_SINGLE_HEADER=ON
cmake --build build
The single header file will be in single_include/CXXStateTree.hpp - just drop it into your project!
Option 2: Shared Library
cmake -S . -B build
cmake --build build
Quick Example: Traffic Light
Letโs build a simple traffic light system:
#include <iostream>
#include <thread>
#include <chrono>
#include "CXXStateTree/StateTree.hpp"
using namespace CXXStateTree;
using namespace std::chrono_literals;
int main() {
auto trafficLight = StateTree::Builder()
.initial("Red")
.state("Red", [](State& s) {
s.on("Timer", "Green", nullptr, []() {
std::cout << "๐ด -> ๐ข RED to GREEN" << std::endl;
});
})
.state("Green", [](State& s) {
s.on("Timer", "Yellow", nullptr, []() {
std::cout << "๐ข -> ๐ก GREEN to YELLOW" << std::endl;
});
})
.state("Yellow", [](State& s) {
s.on("Timer", "Red", nullptr, []() {
std::cout << "๐ก -> ๐ด YELLOW to RED" << std::endl;
});
})
.build();
// Simulate traffic light cycle
for (int i = 0; i < 6; i++) {
std::this_thread::sleep_for(2s);
trafficLight.send("Timer");
}
return 0;
}
๐๏ธ Project Quality
CXXStateTree isnโt just elegant code - itโs built with professional software engineering practices:
- โ Google Test Integration - Comprehensive unit test suite
- โ Codecov Integration - Track test coverage
- โ GitHub Actions CI/CD - Every commit is validated
- โ Modern CMake - Easy integration into existing projects
๐บ๏ธ Roadmap
The project has an exciting future ahead:
| Status | Version | Features |
|---|---|---|
| โ | v0.1.0 | Basic state machine with transitions |
| โ | v0.2.0 | Guards and actions |
| โ | v0.3.0 | Nested hierarchical states |
| โ | v0.4.0 | Graphviz export |
| ๐ง | v0.5.0 | Coroutine/async support |
| ๐ | v1.0.0 | Full test coverage, benchmarks, docs |
๐ค Contributing
CXXStateTree is open source under the MPL 2.0 license and welcomes contributions!
Ways to contribute:
- ๐ Report bugs and issues
- ๐ก Suggest new features
- ๐ง Submit pull requests
- ๐ Improve documentation
- โก Share performance benchmarks
๐ Learning Resources
Want to dive deeper? Check out:
- GitHub Repository
- Examples Directory
- Test Suite - Great for understanding usage patterns
๐ญ Final Thoughts
State machines donโt have to be a pain in C++. With CXXStateTree, you get:
- Developer Productivity - Write less, express more
- Maintainability - Clear structure that scales
- Performance - Zero-overhead abstractions
- Modern C++ - Built for C++20 and beyond
- Active Development - Regular updates and improvements
Whether youโre building a game, an embedded system, or a complex business application, CXXStateTree provides a solid foundation for managing state transitions cleanly and efficiently.
๐ Try It Today
git clone https://github.com/ZigRazor/CXXStateTree.git
Give it a star โญ if you find it useful, and share your experience in the comments below!
What kind of state machines are you building? Drop a comment and letโs discuss! ๐ฌ