Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- template<typename Owner>
- class Comparable;
- template<typename Owner>
- bool operator<(Comparable<Owner> const& left, Comparable<Owner> const& right)
- {
- return left.owner().data() < right.owner().data();
- }
- template<typename Owner>
- bool operator>(Comparable<Owner> const& left, Comparable<Owner> const& right)
- {
- return left.owner().data() > right.owner().data();
- }
- template<typename Owner>
- bool operator<=(Comparable<Owner> const& left, Comparable<Owner> const& right)
- {
- return left.owner().data() <= right.owner().data();
- }
- template<typename Owner>
- std::ostream& operator<<(std::ostream& s, Comparable<Owner> const& c)
- {
- s << c.owner().name() << "(" << c.owner().data() << ")";
- return s;
- }
- template<typename Owner>
- class Comparable
- {
- public:
- Owner const& owner() const
- {
- return *static_cast<Owner const * const>(this);
- }
- };
- class Timestamp : public Comparable<Timestamp>
- {
- public:
- unsigned int _timestamp;
- unsigned int const& data() const
- {
- return _timestamp;
- }
- const char* name() const
- {
- return "Timestamp";
- }
- };
- class Interval : public Comparable<Interval>
- {
- public:
- unsigned int _interval;
- unsigned int const& data() const
- {
- return _interval;
- }
- const char* name() const
- {
- return "Interval";
- }
- };
- /*
- oleg (0) ~$ g++ test.cpp && ./a.out
- Timestamp(5)<Timestamp(6) is true
- Timestamp(5)>Timestamp(6) is false
- Timestamp(5)<=Timestamp(6) is true
- */
- int main(int, char*[])
- {
- Timestamp lt, rt;
- Interval li, ri;
- lt._timestamp = 5;
- rt._timestamp = 6;
- li._interval = 7;
- ri._interval = 8;
- std::cout << lt << "<" << rt << " is " << (lt < rt ? "true" : "false") << std::endl;
- std::cout << lt << ">" << rt << " is " << (lt > rt ? "true" : "false") << std::endl;
- std::cout << lt << "<=" << rt << " is " << (lt <= rt ? "true" : "false") << std::endl;
- /*
- std::cout << lt << " < " << ri << " is incomparable " << (lt < ri ? "true" : "false") << std::endl;
- Error of compiler:
- oleg (0) ~$ g++ test.cpp
- test.cpp: In function ‘int main(int, char**)’:
- test.cpp:87:68: error: no match for ‘operator<’ in ‘lt < ri’
- test.cpp:87:68: note: candidate is:
- test.cpp:7:6: note: template<class Owner> bool operator<(const Comparable<Owner>&, const Comparable<Owner>&)
- test.cpp:7:6: note: template argument deduction/substitution failed:
- test.cpp:87:68: note: deduced conflicting types for parameter ‘Owner’ (‘Timestamp’ and ‘Interval’)
- */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement