Skip to content

Instantly share code, notes, and snippets.

@AlexisTM
Last active July 15, 2022 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexisTM/833346e077d9ebe72ad0f081db942522 to your computer and use it in GitHub Desktop.
Save AlexisTM/833346e077d9ebe72ad0f081db942522 to your computer and use it in GitHub Desktop.
C++ Tri-state enum method which is nice to use, but bad to write.
#include <stdint.h>
#include <stdio.h>
// The processes vision can be running
enum struct Process : uint16_t {
PROCESS_1,
PROCESS_2,
};
enum struct Function : uint16_t {
FUNCTION_1,
FUNCTION_2,
};
// The steps building the function.
namespace steps {
enum struct Function_1 : uint16_t {
IDLE,
STARTUP,
SHUTDOWN,
};
enum struct Function_2 : uint16_t {
INIT,
DOING_STUFF,
ABORTED,
};
} // namespace steps
union Step {
steps::Function_1 func_1;
steps::Function_2 func_2;
uint16_t value;
};
struct Status {
Process process;
Function function;
Step step;
};
#define STEP(name, config) \
static Status name() { \
return {process_, function_, {.value = static_cast<uint16_t>(config)}}; \
}
namespace Process1 {
static constexpr Process process_ = Process::PROCESS_1;
namespace Function1 {
static constexpr Function function_ = Function::FUNCTION_1;
STEP(Idle, steps::Function_1::IDLE)
STEP(Startup, steps::Function_1::STARTUP)
STEP(Shutdown, steps::Function_1::SHUTDOWN)
};
};
namespace Process2 {
static constexpr Process process_ = Process::PROCESS_2;
namespace Function1 {
static constexpr Function function_ = Function::FUNCTION_1;
STEP(Idle, steps::Function_1::IDLE)
STEP(Startup, steps::Function_1::STARTUP)
STEP(Shutdown, steps::Function_1::SHUTDOWN)
};
namespace Function2 {
static constexpr Function function_ = Function::FUNCTION_2;
STEP(Idle, steps::Function_2::INIT)
STEP(Startup, steps::Function_2::DOING_STUFF)
STEP(Shutdown, steps::Function_2::ABORTED)
};
};
#undef STEP
int main() {
Status status = Process2::Function1::Shutdown();
printf("Status: %d %d %d\n", (uint16_t) status.process, (uint16_t) status.function, status.step.value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment