-1

I have got strongly typed enum.

enum class CustomCommand : unsigned char
{
    ENQ = 0x05,
    ACK = 0x06,
    NAK = 0x15,
};

And the function like:

void print_byte(unsigned char byte)
{
    cout << "Byte: " << byte << endl;
}

But when I call the function, GCC throw an error like:

/home/ser/QTProjects/SerialPort/main.cpp:27: error: cannot convert 'CustomCommand' to 'unsigned char' for argument '1' to 'void print_byte(unsigned char)'
     print_byte(CustomCommand::ACK);
                                  ^

Why I always need to manually cast CustomCommand enum when I gave it unsigned char type?

Ruslan Skaldin
  • 981
  • 16
  • 29
  • Possible duplicate of [How to automatically convert strongly typed enum into int?](http://stackoverflow.com/questions/8357240/how-to-automatically-convert-strongly-typed-enum-into-int) –  Nov 10 '16 at 05:04
  • Because you wanted exactly that when you chose strongly typed enum over classical enum. – n. m. could be an AI Nov 10 '16 at 05:31

1 Answers1

2

The purpose of the c++ type system is to help tired and ADHA programmers not to mix bool and pants. (or in this case CustomCommand and char)

You must try and pass the enum "object" around as long as possible and cast only at the last point of use. As an example you could overload the print_byte function:

void print_byte(CustomCommand  cmd)
 {
     std::cout << static_cast<unsigned char>(cmd);
 };
SVictor
  • 66
  • 3
  • Actually I'd prefer to add an output operator for `CustomCommand`, and then use `std::cout << cmd;` Indeed, when being ambitious, one could even implement an "commandalpha" manipulator similar to `boolalpha` that allows to output either the numerical value, or the enumerator names. – celtschk Nov 10 '16 at 07:44
  • @celtschk, I agree, but I think the OP must first get an understanding of the usefulness and application of the enum class. Overloading of stream operators, type traits, etc. will come in time. – SVictor Nov 10 '16 at 08:29