跳到主要内容

Cpp Weekly Lambdas As State Machines

· 阅读需 1 分钟
Bruce
Back End Engineer

使用Lambads实现状态机

Code

#include <format>
#include <exception>
#include <variant>
#include <iostream>

auto int_parser() {
enum class ParseState {
StartUp,
Numbers,
Invalid,
};
return [value = 0, state = ParseState::StartUp, is_negative = false](char input)mutable ->std::variant<int,char> {
switch (state)
{
case ParseState::StartUp:
if (input == '-') {
is_negative = true;
state = ParseState::Numbers;
return value;
}
[[fallthrough]];
case ParseState::Numbers:
if (input >= '0' && input <= '9') {
value = value * 10 + (input - '0');
return (is_negative)? -1*value:value;
}
state = ParseState::Invalid;
return input;
case ParseState::Invalid:
return input;
default:
return input;
}
};
}

int main() {

auto parser = int_parser();

parser('-');
parser('3');
parser('0');

auto res = parser('1');

std::cout << std::get<int>(res) << std::endl;// -301

return 0;
}