Is it possible to manually define a conversion for an enum class?

前端 未结 3 2240
自闭症患者
自闭症患者 2020-12-30 18:37

Normally you can define a cast for a class by using the following syntax:

class Test {
public:
  explicit operator bool() { return false; }
};
3条回答
  •  遥遥无期
    2020-12-30 19:08

    You cant define non-member cast operators in C++. And you certainly cant define member functions for enums. So I suggest you do free functions to convert your enum to other types, the same way you would implement cast operators.

    e.g.

    bool TestToBool(enum_e val)
    {
        return false;
    }
    
    const char *TestToString(enum_e val)
    {
        return "false";
    }
    

    There is a nice way of associating those enums to bools, you have to split it on two files .h and .cpp. Here it is if it helps:

    enum.h

    ///////////////////////////////
    // enum.h
    #ifdef CPP_FILE
    #define ENUMBOOL_ENTRY(A, B)            { (enum_e) A, (bool) B },
    struct EnumBool
    {
        enum_e  enumVal;
        bool    boolVal;
    };
    #else
    #define ENUMBOOL_ENTRY(A, B)            A,
    #endif
    
    
    #ifdef CPP_FILE
    static EnumBool enumBoolTable[] = {
    #else
    enum enum_e
    {
    #endif
    ENUMBOOL_ENTRY(ItemA, true),
    ENUMBOOL_ENTRY(ItemB, false),
    ...
    };
    
    bool EnumToBool(enum_e val);
    

    enum.cpp

    ///////////////////////////////
    // enum.cpp
    #define CPP_FILE
    #include "enum.h"
    
    bool EnumToBool(enum_e val)
        //implement
    

    I didnt compile it so take it easy if it has any errors :).

提交回复
热议问题