namespaces for enum types - best practices

前端 未结 8 1919
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 06:34

Often, one needs several enumerated types together. Sometimes, one has a name clash. Two solutions to this come to mind: use a namespace, or use \'larger\' enum element na

8条回答
  •  暖寄归人
    2020-12-04 06:51

    I've hybridized the preceding answers to something like this: (EDIT: This is only useful for pre- C++11. If you are using C++11, use enum class)

    I've got one big header file that contains all my project enums, because these enums are shared between worker classes and it doesn't make sense to put the enums in the worker classes themselves.

    The struct avoids the public: syntactic sugar, and the typedef lets you actually declare variables of these enums within other worker classes.

    I don't think using a namespace helps at all. Maybe this is because I'm a C# programmer, and there you have to use the enum type name when referring the values, so I'm used to it.

        struct KeySource {
            typedef enum { 
                None, 
                Efuse, 
                Bbram
            } Type;
        };
    
        struct Checksum {
            typedef enum {
                None =0,
                MD5 = 1,
                SHA1 = 2,
                SHA2 = 3
            } Type;
        };
    
        struct Encryption {
            typedef enum {
                Undetermined,
                None,
                AES
            } Type;
        };
    
        struct File {
            typedef enum {
                Unknown = 0,
                MCS,
                MEM,
                BIN,
                HEX
            } Type;
        };
    

    ...

    class Worker {
        File::Type fileType;
        void DoIt() {
           switch(fileType) {
           case File::MCS: ... ;
           case File::MEM: ... ;
           case File::HEX: ... ;
        }
    }
    

提交回复
热议问题