Setting an int to Infinity in C++

前端 未结 6 1186
终归单人心
终归单人心 2020-12-12 10:28

I have an int a that needs to be equal to \"infinity\". This means that if

int b = anyValue;

a>b is always tru

6条回答
  •  醉话见心
    2020-12-12 10:47

    int is inherently finite; there's no value that satisfies your requirements.

    If you're willing to change the type of b, though, you can do this with operator overrides:

    class infinitytype {};
    
    template
    bool operator>(const T &, const infinitytype &) {
      return false;
    }
    
    template
    bool operator<(const T &, const infinitytype &) {
      return true;
    }
    
    bool operator<(const infinitytype &, const infinitytype &) {
      return false;
    }
    
    
    bool operator>(const infinitytype &, const infinitytype &) {
      return false;
    }
    
    // add operator==, operator!=, operator>=, operator<=...
    
    int main() {
      std::cout << ( INT_MAX < infinitytype() ); // true
    }
    

提交回复
热议问题