Ternary comparison operator overloading

前端 未结 2 1951
不思量自难忘°
不思量自难忘° 2021-01-14 18:24

How would one implement a ternary comparison operator to determine, for example, the boolean value of a < b < c?

2条回答
  •  轮回少年
    2021-01-14 19:11

    Solution: When coding a comparison, have the return type be a comparison object that can chain additional comparisons, but is implicitly convertible to a bool. This can even (kind of) work with types that weren't coded with this intent, simply by casting them to the comparison type manually.

    Implementation:

    template
    class comparison {
      const bool result;
      const T& last;
    public:
      comparison(const T& l, bool r=true) :result(r), last(l) {}
      operator bool() const {return result;}
      comparison operator<(const T& rhs) const {return comparison(rhs, (result && last(const T& rhs) const {return comparison(rhs, (result && last>rhs));}
      comparison operator>=(const T& rhs) const {return comparison(rhs, (result && last>=rhs));}
    };
    

    A useful example:

    #include 
    int main() {
      //testing of chained comparisons with int
      std::cout << (comparison(0) < 1 < 2) << '\n';
      std::cout << (comparison(0) < 1 > 2) << '\n';
      std::cout << (comparison(0) > 1 < 2) << '\n';
      std::cout << (comparison(0) > 1 > 2) << '\n';
    }
    

    Output:

    1
    0
    0
    0
    

    Note: This was created by Mooing Duck, and a compiled, more robust example can be found on http://ideone.com/awrmK

提交回复
热议问题