简体   繁体   中英

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)'
     print_byte(CustomCommand::ACK);
                                  ^

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM