Home > Blockchain >  How to use value of a class enum : char as a char argument of function?
How to use value of a class enum : char as a char argument of function?

Time:10-28

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:

  1. To make it easy for code completion to suggest these hard-coded constant values
  2. To be able to reuse the same names, but keep them namespaced cleanly within their own enum
  3. To make it easy for a programmer to just select a code and pass it to the function without thinking too hard about it.

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';
};

CodePudding user response:

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).

CodePudding user response:

How to use value of a class enum : char as a char argument of function?

An enum class can be converted to an integer using static_cast:

sendRemoteAudioMessage(static_cast<char>(SoundFileCode::LOADING_READY));

(preferably without having to cast anything to make it a cleaner API):

Ideal solution for a cleaner API is to use the matching parameter type:

void sendRemoteAudioMessage(SoundFileCode audioCode)
  • Related