I have some functions that can return either success or one of a fixed set of error codes. To identify the error codes, I had (something like) this old-school C-style enum declared:
enum {
RESULT_ERROR_BAD_PARAMETER = -3,
RESULT_ERROR_FILE_NOT_FOUND = -2,
RESULT_ERROR_GENERAL = -1,
RESULT_SUCCESS = 0
};
typedef int my_status_t;
my_status_t MyFunc(); // returns a RESULT_* value
This worked pretty well; the calling pattern would be something like:
if (MyFunc() != RESULT_SUCCESS) printf("Error!\n");
... however it was uncomfortably permissive about allowing implicit conversions of my_status_t
values to int/bool/etc, allowing careless mistakes like this:
// Compiles but does the wrong thing at run-time -- bad!
if (MyFunc() == false) printf("Error!\n");
... so in my new code revision, I converted it to be an enum class
instead:
enum class my_status_t {
RESULT_ERROR_BAD_PARAMETER = -3,
RESULT_ERROR_FILE_NOT_FOUND = -2,
RESULT_ERROR_GENERAL = -1,
RESULT_SUCCESS = 0
};
... this works great from a compile-time checking perspective; now most unintentional type-promotions are caught by the compiler, forcing the programmer to go back and do it the right way.
The only thing that bothers me is that the new syntax is tedious: now I have to write something like:
if (MyFunc() != my_status_t::RESULT_SUCCESS) printf("Error!\n");
... at every call site -- having to type out my_status_t::
each time is tedious and makes the code harder to read, without really adding much value (since RESULT_SUCCESS
is sufficiently unique for my purposes on its own, anyway)
My question is, is there some kind of using namespace my_status_t;
style directive I could use to tell the compiler to export the enum-values out of their my_status_t
namespace, so that I could reference them without having to type the my_status_t::
prefix all the time?
Aucun commentaire:
Enregistrer un commentaire