简体   繁体   中英

Relational operator overloading in a templated class (C++)

I am creating a KeyValuePair class, and am running into some trouble when overloading the relational operators. It is my understanding that this is necessary for using the std sort functions (I am trying to have sort based on the values)

Here is the header:

template <typename K, typename V>
class KeyValuePair
{
public:
    //factory
    static KeyValuePair<K,V>* newKeyValuePair(K key, V value);  
    //getters
    const K &Key() const;
    const V &Value() const;
    //setter
    V &Value();

    //The problem
    bool operator<(const KeyValuePair<K,V> &rhs);

    string toString();
    ~KeyValuePair(void);
private:
    K key;
    V value;
    KeyValuePair(K key, V value);
    KeyValuePair(void);
};

Here is the definition of the < function

template <typename K, typename V>
bool KeyValuePair<K,V>::operator<(const KeyValuePair<K,V> &rhs)
{
    return value < rhs.Value();
}

And here is the main where I am just testing the functionality of the class.

int _tmain(int argc, _TCHAR* argv[])
{
    KeyValuePair<char,int>* kvp1 = KeyValuePair<char, int>::newKeyValuePair('A',1);
    KeyValuePair<char,int>* kvp2 = KeyValuePair<char,int>::newKeyValuePair('B',10);
    cout << (kvp1 < kvp2) << "\n";
    return 0;
}

I have a breakpoint at the < function in my KeyValuePair class, and it is never activated.

Any Ideas? Thanks in advance.

kvp1 and kvp2 are pointers to KeyValuePair<char, int> objects. They are not themselves KeyValuePair<char, int> objects.

*kvp1 < *kvp2 would invoke your overloaded operator< . You cannot overload operator< for two pointer types because the built-in operator< for pointers will be used.

std::pair can be used as a key-value pair. In any case, you almost certainly shouldn't be dynamically creating objects of this type: you should prefer to avoid dynamic allocation wherever possible, especially explicit dynamic allocation. Instead, just use KeyValuePair<char, int> local variables:

KeyValuePair<char, int> kvp1('A', 1);
KeyValuePair<char, int> kvp2('B', 10);
std::cout << (kvp1 < kvp2) << "\n"; // calls your operator< overload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM