You will have to map the string values (chain of characters) to a corresponding enum value (integer). Here's how you would do this in practice using std::map
:
Demo
#include <cstdio>
#include <map>
#include <string_view>
#include <stdexcept>
enum class myenum
{
content_encoding,
content_length,
transfer_encoding,
};
// In C++23 use a constexpr flat_map instead
const std::map<std::string_view, myenum> map_myenum = {
{"content-encoding", myenum::content_encoding},
{"content-length", myenum::content_length},
{"transfer-encoding", myenum::transfer_encoding},
};
auto test(std::string_view str)
{
try {
switch(map_myenum.at(str)) {
case myenum::content_encoding:
printf("String was content_encoding\n");
break;
case myenum::content_length:
printf("String was content_length\n");
break;
case myenum::transfer_encoding:
printf("String was transfer_encoding\n");
break;
}
} catch(const std::out_of_range& e) {
printf("String didn't match any criteria!\n");
}
}
int main()
{
test("content-encoding");
test("content-length");
test("some random other stuff");
}
Output:
String was content_encoding
String was content_length
String didn't match any criteria!
A few notes:
- We use a const map to hint to the compiler that this map isn't supposed to be changed at all. The exception handling is a necessary evil as for const maps we can only use the
.at()
method as it doesn't insert items if it doesn't find the key in the map. It's a bit of an unfortunate decision by the CWG in my view, as this is definitely nothing "exceptional" and we shouldn't have to pay the cost (in this case at least).
- In C++23 we get flat_map which is more suitable in this case, as I suppose it will contain constexpr initializers and assignement which would allow us to lay out the whole map at compile time, so that we just pay the overhead of copy-pasting the final map to RAM. It's also a lot more cache-friendly.