In an endeavor to write cleaner code I'm (likely over-)using enums
, like so:
enum class SoundFileCode : char {
PC_STARTUP = '1', // probably never used
LOADING_READY = '2',
VOICE_RECOGNITION_ON = '3',
VOICE_RECOGNITION_OFF = '4',
DISPENSING = '5'
};
I'd like to be able to pass that value to a function in a nice clean way (preferably without having to cast anything to make it a cleaner API):
sendRemoteAudioMessage(SoundFileCode::LOADING_READY);
Here's the function signature:
void sendRemoteAudioMessage(char audioCode){ }
I see you shaking your head. You already know the error I'm going to get: Compilation error: cannot convert 'SoundFileCode' to 'char' for argument '1' to 'void sendRemoteAudioMessage(char)'
My goals are:
If enums won't foot the bill here, what's a good approach? Creating a class with some static constants? (this is likely how I'd approach it in PHP / Java)
UPDATE
The following (if somewhat verbose) approach compiles and runs fine. Is there a superior approach?
class SoundFileCode {
public :
static const char PC_STARTUP = '1';
static const char LOADING_READY = '2';
static const char VOICE_RECOGNITION_ON = '3';
static const char VOICE_RECOGNITION_OFF = '4';
static const char DISPENSING = '5';
};
enum class
purposefully disallows implicit casts to the underlying type, so you'd either need static_cast<>
, or - preferably - take the enum in the callee.
If neither of the above works, e.g. because the functions you call are in a library, you can still do the old trick of wrapping the enum
into a namespace
(or class
):
namespace SoundFileCode {
enum type : char {
PC_STARTUP = '1',
// ...
}
}
In this case, you'll still have SoundFileCode::PC_STARTUP
for the name of the enum value, but you can implicitly cast to char
. An inconvenience is that now you need SoundFileCode::type
in declarations of the enum (and other places where the type is used):
int main() {
SoundFileCode::type sfc = SoundFileCode::PC_STARTUP;
sendRemoteAudioMessage(sfc);
sendRemoteAudioMessage(SoundFileCode::PC_STARTUP);
}