intrigued_66
intrigued_66

Reputation: 17248

C++ Set enum class value according to two chars

I have a field in a message header which denotes the message type. The field is two chars, like "AR". I'd like to represent this using an enum class so I can enforce all types are handled on a switch statement.

Inside the enum class we will see the enum's value is defined by the two char values. However, I'm struggling because it must be a constexpr.

This doesn't compile but I'm after something like this:

enum class AnEnum : uint16_t
{
    value_one = atoi(std::string("AR").c_str()),
    value_two = atoi(std::string("PF").c_str())
};

In the above example one message header contains the chars AR and another message type contains PF.

Upvotes: 0

Views: 270

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122585

atoi converts integer string representations to integers. "AR" and "PR" arent integers, hence atoi is not what you want.

Thanks to bitmask this is what you do want:

enum class AnEnum : std::uint16_t
{
    value_one = std::uint16_t{'A'*256+'R'},
    value_two = std::uint16_t{'P'*256+'F'}
};

For a string recieved in a message you do not need to convert it at compile time because the string is only known at runtime. Only to avoid duplication it is handy to have it at compile time so that the same conversion can be used for the enum values.

constexpr std::uint16_t convert(const char x[2]) {
    return x[0]*256+x[1];
}

enum class AnEnum : std::uint16_t
{
    value_one = convert("AR"),
    value_two = convert("PF")
};

Complete Example

Upvotes: 1

Cwift
Cwift

Reputation: 310

Well, this is how I implementd:

enum class E {
    AR = 0,
    PF = 1
};
static constexpr const char* ENUM_STRS[] = { "AR", "PF" };

void foo() {
    using std::cout;
    using std::endl;
    E e = E::PF;
    switch (e) {
    case E::AR:
        cout << ENUM_STRS[static_cast<int>(e)] << endl;
        break;
    case E::PF:
        cout << ENUM_STRS[static_cast<int>(e)] << endl;
        break;
    default:
        break;
    }
}

Upvotes: 1

Related Questions