Certainly! Below is an example of a modern C++ generic state machine implemented using templates and lambdas. The state machine is entirely static—everything that can be static is static. This implementation leverages C++17 and C++20 features like class template argument deduction, constexpr functions, and non-type template parameters (NTTP) with lambdas.
#include <iostream>
#include <type_traits>
// Base case for Empty State (Terminating State)
struct EmptyState {
static constexpr bool execute(const char* input) {
return true; // Accepting state
}
};
// Transition class template
template<char Input, typename NextState>
struct Transition {
static constexpr char input = Input;
using next_state = NextState;
};
// State class template
template<
auto Operation, // The operation lambda associated with the state
typename... Transitions // Variadic list of possible transitions
>
struct State {
// Static constexpr execute function
static constexpr bool execute(const char* input) {
Operation(); // Execute the state's operation
if constexpr (sizeof...(Transitions) > 0) {
return execute_transitions<Transitions...>(input);
} else {
return true; // No transitions, accepting state
}
}
private:
// Recursive helper function to evaluate transitions
template<typename Transition, typename... Rest>
static constexpr bool execute_transitions(const char* input) {
if (*input == '\0') {
return false; // End of input, no more transitions
}
if (Transition::input == *input) {
return Transition::next_state::execute(input + 1);
} else if constexpr (sizeof...(Rest) > 0) {
return execute_transitions<Rest...>(input);
} else {
return false; // No matching transitions
}
}
};
// Sample operations as lambdas
constexpr auto operation1 = []() { std::cout << "In State 1\n"; };
constexpr auto operation2 = []() { std::cout << "In State 2\n"; };
constexpr auto operation3 = []() { std::cout << "In State 3\n"; };
constexpr auto accepting_operation = []() { std::cout << "In Accepting State\n"; };
// Define the states of the state machine
struct AcceptingState : State<accepting_operation> {};
struct State3 : State<
operation3,
Transition<'c', AcceptingState>
> {};
struct State2 : State<
operation2,
Transition<'b', State3>
> {};
struct State1 : State<
operation1,
Transition<'a', State2>
> {};
// Function to test the state machine at compile-time
constexpr bool test_state_machine(const char* input) {
return State1::execute(input);
}
// Main function
int main() {
// Input string known at compile time
constexpr const char* input = "abc";
// Compile-time evaluation
static_assert(test_state_machine(input), "Input not accepted by state machine!");
// Runtime output
if (test_state_machine(input)) {
std::cout << "Input accepted by state machine.\n";
} else {
std::cout << "Input rejected by state machine.\n";
}
return 0;
}
Explanation:
-
State Class Template:
- Each state is represented by a
State class template that takes an Operation (a lambda) and a variadic list of Transitions.
- The
execute function is constexpr, allowing it to be evaluated at compile time.
- The
execute_transitions helper function recursively checks if any transition matches the current input character.
-
Transition Struct:
- Represents a transition from one state to another based on an input character.
- Contains a compile-time
input character and a next_state type.
-
Operations:
- Defined as
constexpr lambdas, representing actions performed in each state.
- Can capture variables if needed, but they must also be
constexpr.
-
State Definitions:
AcceptingState is a state with no transitions, representing the successful end of the state machine.
State1, State2, and State3 are defined with their respective operations and transitions.
-
Compile-Time Testing:
- The
test_state_machine function runs the state machine at compile time.
static_assert is used to ensure that the input string is accepted by the state machine during compilation.
- This guarantees that if the input string does not meet the state machine's criteria, the code will fail to compile.
-
Runtime Output:
- Even though the state machine logic is evaluated at compile time, we can also output messages at runtime for verification.
Key Points:
-
Entirely Static:
- All state machine logic, state transitions, and operations are known at compile time.
- The use of
constexpr ensures that computations occur during compilation.
-
Templates and Lambdas:
- Templates are heavily used to define the structure of the state machine.
- Lambdas are passed as non-type template parameters (NTTP), which is allowed in C++20 for lambdas with no captures.
-
Modern C++ Features:
- Utilizes features from C++17 and C++20, like
constexpr lambdas and class template argument deduction.
- By using these features, we can write expressive and efficient compile-time code.
-
Flexibility:
- The state machine is generic and can be extended with additional states, transitions, and operations.
- Conditions and inputs can be modified as needed, as long as they are known at compile time.
Notes:
Example Usage:
Suppose you want to create a state machine that accepts the string "hello". Here's how you might define it:
// New operations
constexpr auto op_start = [](){ std::cout << "Start State\n"; };
constexpr auto op_h = [](){ std::cout << "State H\n"; };
constexpr auto op_e = [](){ std::cout << "State E\n"; };
constexpr auto op_l1 = [](){ std::cout << "State L1\n"; };
constexpr auto op_l2 = [](){ std::cout << "State L2\n"; };
constexpr auto op_o = [](){ std::cout << "State O\n"; };
// State definitions
struct StateO : State<op_o, Transition<'\0', AcceptingState>> {};
struct StateL2 : State<op_l2, Transition<'o', StateO>> {};
struct StateL1 : State<op_l1, Transition<'l', StateL2>> {};
struct StateE : State<op_e, Transition<'l', StateL1>> {};
struct StateH : State<op_h, Transition<'e', StateE>> {};
struct StartState : State<op_start, Transition<'h', StateH>> {};
// Test the state machine
constexpr bool test_hello_state_machine(const char* input) {
return StartState::execute(input);
}
int main() {
constexpr const char* input = "hello";
static_assert(test_hello_state_machine(input), "Input not accepted!");
if (test_hello_state_machine(input)) {
std::cout << "Input accepted: " << input << "\n";
} else {
std::cout << "Input rejected: " << input << "\n";
}
return 0;
}
Conclusion:
This implementation demonstrates how to create a generic, entirely static state machine in modern C++ using templates and lambdas. By leveraging compile-time features, we ensure that all computations and state transitions are resolved during compilation, resulting in efficient and predictable code.
Feel free to adapt and extend this pattern to suit your specific needs!