Reputation: 871
I am working on heap implementation. It has to be template class and I need it to have its own comparator, passed in constructor. How can I do it?
I've tried this:
template <typename T>
class Heap{
public:
Heap(int size, bool (*comparator) (const T & a, const T & b) = [] (const T & a, const T & b){
return a < b;
})
// other unimportant methods
}
Which works for:
Heap<int> heap(4);
And also for:
Heap<int> heap(4, [](const int & a, const int & b){ return false; })
But when I try to use it with pointers like this (where offer is some structure):
Heap<Offer*> heap2(3, [](Offer const * a, Offer const * b){
return false;
});
I got this compilation error:
test.cpp: In function ‘int main()’:
test.cpp:126:3: error: invalid user-defined conversion from ‘main()::<lambda(const Offer*, const Offer*)>’ to ‘bool (*)(Offer* const&, Offer* const&)’ [-fpermissive]
});
^
test.cpp:124:59: note: candidate is: main()::<lambda(const Offer*, const Offer*)>::operator bool (*)(const Offer*, const Offer*)() const <near match>
Heap<Offer*> heap2(3, [](Offer const * a, Offer const * b){
^
test.cpp:124:59: note: no known conversion from ‘bool (*)(const Offer*, const Offer*)’ to ‘bool (*)(Offer* const&, Offer* const&)’
test.cpp:13:5: note: initializing argument 2 of ‘Heap<T>::Heap(int, bool (*)(const T&, const T&)) [with T = Offer*]’
Heap(int size, bool (*comparator) (const T & a, const T & b) = [] (const T & a, const T & b){
How to make it work for both of scenarios?
Upvotes: 4
Views: 327
Reputation: 1736
For the pointer version: 'T' is a pointer then that needs to passed as a const ref - it's not the datum it points to that is to be const qualified here, but the pointer ref itself.
template <typename T>
class Heap{
public:
Heap(int size, bool (*comparator) (const T & a, const T & b)
= [] (const T & a, const T & b){
return a < b;
}) {};
// other unimportant methods
};
int main()
{
Heap<int*> heap2(3, [](int* const& a, int* const& b){
return false;
});
// analogous to
Heap<int> heap(4, [](const int & a, const int & b){
return false;
});
// but it's the pointer to the datum in the first,
// and the datum itself in the latter case
}
Upvotes: 3