Can a C++ enum class have methods?

前端 未结 7 782
抹茶落季
抹茶落季 2020-12-12 17:44

I have an enum class with two values, and I want to create a method which receives a value and returns the other one. I also want to maintain type safety(that\'s why I use e

7条回答
  •  萌比男神i
    2020-12-12 18:30

    Based on jtlim's answer

    Idea (Solution)

    enum ErrorType: int {
      noConnection,
      noMemory
    };
    
    class Error {
    public:
      Error() = default;
      constexpr Error(ErrorType type) : type(type) { }
    
      operator ErrorType() const { return type; }
      constexpr bool operator == (Error error) const { return type == error.type; }
      constexpr bool operator != (Error error) const { return type != error.type; }    
      constexpr bool operator == (ErrorType errorType) const { return type == errorType; }
      constexpr bool operator != (ErrorType errorType) const { return type != errorType; }
    
      String description() { 
        switch (type) {
        case noConnection: return "no connection";
        case noMemory: return "no memory";
        default: return "undefined error";
        }
     }
    
    private:
      ErrorType type;
    };
    

    Usage

    Error err = Error(noConnection);
    err = noMemory;
    print("1 " + err.description());
    
    switch (err) {
      case noConnection: 
        print("2 bad connection");
        break;
      case noMemory:
        print("2 disk is full");
        break;
      default: 
        print("2 oops");
        break;
    }
    
    if (err == noMemory) { print("3 Errors match"); }
    if (err != noConnection) { print("4 Errors don't match"); }
    

提交回复
热议问题