Reputation: 103
I'm creating a container that works like the STL using an array. One thing I am stuck on is how to implement a comparator object to the template
template <typename K, typename V, typename KeyEqual = myEqualObject<K> >
class Map {
......
}
would that template header need to be repeated on all method bodies outside of the class ? i.e
template <typename K, typename V >
V& Map<K,V>::operator[] (K key) {
...
}
should be
template <typename K, typename V, typename KeyEqual = myEqualObject<K> >
V& Map<K,V>::operator[] (K key) {
...
}
Also I am struggling with how to use/implement this extra object in my class to check if two key values are the same. Can anyone shed any light ?
I have looked around this subject but cannot find any examples in this context
Upvotes: 0
Views: 2467
Reputation: 254431
would that template header need to be repeated on all method bodies outside of the class ?
You need all the template parameters, but there's no need to repeat the default arguments:
template <typename K, typename V, typename KeyEqual>
V& Map<K,V,KeyEqual>::operator[] (K key) {
...
}
Also I am struggling with how to use/implement this extra object in my class to check if two key values are the same.
Following the example of the standard containers, store a comparator object in a (probably private) member variable:
KeyEqual equal;
initialise it in the constructor(s), allowing the user to supply one:
Map(/* arguments, */ KeyEqual equal = KeyEqual()) :
// initialisers,
equal(equal)
{
// anything else
}
and use it as a binary predicate:
if (equal(key1, key2)) {
// treat them as equal
}
It can be implemented as a binary function class:
template <typename K> struct myEqualObject {
bool operator()(K const & k1, K const & k2) {return k1 == k2;}
};
although I'd use std::equal_to<K>
as the default, rather than rewriting my own version.
Upvotes: 4