我正在进行堆实现。它必须是模板类,我需要它有自己的比较器,在构造函数中传递。我该怎么办?
我试过这个:
Heap<int> heap(4);
适用于:
Heap<int> heap(4, [](const int & a, const int & b){ return false; })
还有:
Heap<Offer*> heap2(3, [](Offer const * a, Offer const * b){
return false;
});
但是当我尝试使用像这样的指针(提供是一些结构)时:
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){
我收到了这个编译错误:
<div>
如何让它适用于两种情况?
答案 0 :(得分:3)
对于指针版本:'T'是一个指针,然后需要作为const ref传递 - 它不是指向的数据,这里是const限定的,但指针ref本身。
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
}