Easy way to use variables of enum types as string in C?

前端 未结 19 2049
太阳男子
太阳男子 2020-11-22 08:47

Here\'s what I am trying to do:

typedef enum { ONE, TWO, THREE } Numbers;

I am trying to write a function that would do a switch case sim

19条回答
  •  灰色年华
    2020-11-22 09:09

    Because I prefer not to use macros for all the usual reasons, I used a more limited macro solution that has the advantage of keeping the enum declaration macro free. Disadvantages include having to copy paste the macro defintion for each enum, and having to explicitly add a macro invocation when adding values to the enum.

    std::ostream& operator<<(std::ostream& os, provenance_wrapper::CaptureState cs)
    {
    #define HANDLE(x) case x: os << #x; break;
        switch (cs) {
        HANDLE(CaptureState::UNUSED)
        HANDLE(CaptureState::ACTIVE)
        HANDLE(CaptureState::CLOSED)
        }
        return os;
    #undef HANDLE
    }
    

提交回复
热议问题