views:

107

answers:

2

I have the following code. I need B class to have a min priority queue of AToTime objects. AToTime have operator>, and yet i receive error telling me than there is no operator> matching the operands...

#include <queue>
#include <functional>

using namespace std; 

class B{
//public functions
public:

    B();

    virtual ~B();

//private members
private:

    log4cxx::LoggerPtr      m_logger;

    class AToTime 
    {
    //public functions
    public:
        AToTime(const ACE_Time_Value& time, const APtr a) : m_time(time), m_a(a){}

        bool operator >(const AToTime& other)
        {
            return m_time > other.m_time;
        }

    //public members - no point using any private members here
    public:
        ACE_Time_Value      m_time;
        APtr                m_a;
    };


    priority_queue<AToTime, vector<AToTime>, greater<AToTime> > m_myMinHeap;
};
+7  A: 
    bool operator >(const AToTime& other)

It should be a const function.

    bool operator >(const AToTime& other) const 
KennyTM
+1  A: 

Kenny's answer already shows you how to make this work.

Note that I would prefer to implement binary operators which treat their operands equally (they're not modifying them) as free functions:

inline bool operator>(const AToTime& khs, const AToTime& rhs)
{
  return lhs.m_time > rhs.m_time;
}

Further, usually users expect all relational operators to be present if one of them is there. Since the std library mostly wants operator<, except for equality I'd implement the others on top of operator<:

inline bool operator<(const AToTime& khs, const AToTime& rhs)
{return lhs.m_time < rhs.m_time;}

inline bool operator>(const AToTime& khs, const AToTime& rhs)
{return rhs < lhs;}

inline bool operator<=(const AToTime& khs, const AToTime& rhs)
{return !(lhs > rhs);}

inline bool operator>=(const AToTime& khs, const AToTime& rhs)
{return !(lhs < rhs);}

inline bool operator==(const AToTime& khs, const AToTime& rhs)
{return lhs.m_time == rhs.m_time;}

inline bool operator!=(const AToTime& khs, const AToTime& rhs)
{return !(lhs.m_time == rhs.m_time);}
sbi
You dont need to define these manually. They are defined in utility. You just need to include them and use them. "using namespace std::rel_ops;" http://www.cplusplus.com/reference/std/utility/rel_ops/
Martin York
@Martin: A potential problem with those is that you get them for all the types in your namespace. I haven't seen them used in the wild and haven't used them myself either. Are they used? (Maybe that would make a good CW question?)
sbi