Enums in C++
Based on your input, the target language is C++. Here is the translation of the provided example in Markdown format suitable for Hugo.
Enumerated types (enums) in C++ are a special case of sum types. An enum in C++ is a type with a fixed number of possible values, each associated with a distinct name.
Our enum type ServerState
is defined as follows:
#include <iostream>
#include <string>
#include <unordered_map>
enum ServerState {
StateIdle,
StateConnected,
StateError,
StateRetrying,
NumStates
};
std::unordered_map<ServerState, std::string> stateName = {
{StateIdle, "idle"},
{StateConnected, "connected"},
{StateError, "error"},
{StateRetrying, "retrying"}
};
std::string toString(ServerState state) {
return stateName[state];
}
ServerState transition(ServerState s) {
switch (s) {
case StateIdle:
return StateConnected;
case StateConnected:
case StateRetrying:
// Suppose we check some predicates here to determine the next state…
return StateIdle;
case StateError:
return StateError;
default:
throw std::runtime_error("unknown state: " + std::to_string(s));
}
}
int main() {
ServerState ns = transition(StateIdle);
std::cout << toString(ns) << std::endl;
ServerState ns2 = transition(ns);
std::cout << toString(ns2) << std::endl;
return 0;
}
In C++, enum values are implicitly converted to int
, but C++ offers stronger type-checking compared to some other languages. You have to explicitly cast int
to ServerState
if needed.
To run the program, compile the C++ code and then execute the binary:
$ g++ -o enums enums.cpp
$ ./enums
connected
idle
This gives you an overview of how enums can be used effectively in C++. Now that you understand the basics, you can explore more features of the language.