简体   繁体   English

将强类型枚举传递给函数

[英]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: 但是当我调用该函数时,GCC会抛出如下错误:

/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? 给我无符号字符类型时,为什么总是需要强制转换CustomCommand枚举?

The purpose of the c++ type system is to help tired and ADHA programmers not to mix bool and pants. C ++类型系统的目的是帮助疲倦的ADHA程序员不要混淆布尔值和裤子。 (or in this case CustomCommand and char) (或在本例中为CustomCommand和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: 例如,您可以重载print_byte函数:

void print_byte(CustomCommand  cmd)
 {
     std::cout << static_cast<unsigned char>(cmd);
 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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