Hi there everyone,
I've been reading around regarding the strongly typed enums in C++11.
Peter87 had a similar problem to what I'm facing in this topic: http://www.cplusplus.com/forum/general/74363/
However, I need a more general solution applying to more than just one enum.
What I want to do:
1 2 3 4 5 6 7 8 9 10 11
|
struct example {
enum class status { SUCCESS, FAIL_DB, FAIL_UNIQUE };
status some_func()
{
std::vector<std::string> errormessages;
errormessages[status::SUCCESS] = "Operation successful";
// etc.
return status::SUCCESS;
}
};
|
This does not work because strongly typed enums are not implicitly converted into ints / size_t. The same problem occurs with an unordered_map for pretty much the same reason. Looking at the STL file for std::map it seems that this doesn't require any specific type of key (like size_t for std::vector), and off course doesn't need to hash the key type either, it just sorts using the value.
The workarounds:
As far as I can see there are some workarounds for this:
- Use the plain old enum type (although that causes segmentation faults, but that may be me doing something wrong at the moment).
- Use static_cast:
errormessages[static_cast<size_t>(status::SUCCESS)]
(which seems too verbose for providing this in a library).
- Define constants instead of an enum: (but then the whole thing becomes less transparent because functions could not return type example::status, but have to return ints).
1 2 3 4 5 6 7 8 9 10 11 12
|
struct example
{
static const int SUCCESS = 0;
static const int FAIL_DB = 1;
example()
{
std::vector<std::string> errormessages;
errormessages[status::SUCCESS] = "Operation successful";
// etc.
}
};
|
The question:
Are there any other workarounds and which would be the best one to use (mostly from a library-user perspective)? I suppose using "plain" enums is now not recommended any more because there is a more type safe alternative? Would it be a good practice to wrap enum behaviour in some custom class(es)? Or is there another simple way to implement this kind of transparent functionality that I'm not aware of?
For clarity, at the moment I anticipate only using this behaviour for this purpose, viz. status codes (which would change depending on the operation being performed).
Any thoughts and / or suggestions would be much appreciated.
All the best,
NwN