c++ enum and using them to input from user

前端 未结 3 1998
时光说笑
时光说笑 2021-02-08 05:34

I have an enum in my code that is the following: enum Status {In-Active, Active};. A status object is passed to a Person object as a parameter, so I wa

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-08 06:06

    You can also wrap the enum inside a class and provide operator>>. This is a modified example from this link http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Type_Safe_Enum

    #include 
    
    template
    class safe_enum : public def
    {
    public:
      int val;
      safe_enum(int v) : val(v) {}
    //  inner underlying() const { return val; }
      bool operator == (const safe_enum & s) const { return this->val == s.val; }
      bool operator != (const safe_enum & s) const { return this->val != s.val; }
      bool operator <  (const safe_enum & s) const { return this->val <  s.val; }
      bool operator <= (const safe_enum & s) const { return this->val <= s.val; }
      bool operator >  (const safe_enum & s) const { return this->val >  s.val; }
      bool operator >= (const safe_enum & s) const { return this->val >= s.val; }
    };
    
    struct status_def {
      enum type { NoValue, InActive, Active };
    };
    typedef safe_enum Status;
    
    std::istream& operator>>(std::istream& Istr, Status& other)
    {
        std::cout << "Enter Status value: " << std::endl; 
        //here the logic to handle input error
        Istr >> other.val;
        return Istr;
    }
    
    std::ostream& operator<<(std::ostream& os,const Status& toPrint)
    {
        if (toPrint.val == Status::Active)
            return os << "Active";
        if (toPrint.val == Status::NoValue)
            return os << "NoValue";
        if (toPrint.val == Status::InActive)
            return os << "InActive";
        throw;
    }
    
    int main(void)
    {
        Status test(Status::NoValue);
        std::cout << test << std::endl;
        std::cin >> test;
        std::cout << test << std::endl;
    }
    

提交回复
热议问题