Russell Sk. Russell Sk. - 1 year ago 97
C++ Question

Pass strongly typed enum to function

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

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

Answer Source

Cast it to unsigned char:

print_byte(static_cast<unsigned char>(CustomCommand::ACK));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download