I would like to inherit from STL priority queue to have some additional functionality such as: allowing removal. But I am struggling to make this work when I use custom comparators. MWE:
#include <queue>
template<typename T, class Container=std::vector<T>, class Compare=std::less<typename Container::value_type>>
class custom_priority_queue : public std::priority_queue<T, Container, Compare>
{
public:
// My additional functions here.
};
int main()
{
auto pq_comp = [](const int& a, const int& b) { return a <= b; };
std::priority_queue<int, std::vector<int>, decltype(pq_comp)> pq(pq_comp); // works
custom_priority_queue<int> pq_custom; // works
custom_priority_queue<int, std::vector<int>, decltype(pq_comp)> pq_custom2(pq_comp); // Error
return 0;
}
The error is:
main.cpp: In function ‘int main()’:
main.cpp:15:87: error: no matching function for call to ‘custom_priority_queue, main():: >::custom_priority_queue(main()::&)’
15 | custom_priority_queue<int, std::vector<int>, decltype(pq_comp)> pq_custom2(pq_comp); // Error
| ^
main.cpp:4:7: note: candidate: ‘custom_priority_queue, main():: >::custom_priority_queue(const custom_priority_queue, main():: >&)’
4 | class custom_priority_queue : public std::priority_queue<T, Container, Compare>
| ^~~~~~~~~~~~~~~~~~~~~
main.cpp:4:7: note: no known conversion for argument 1 from ‘main()::’ to ‘const custom_priority_queue, main():: >&’
main.cpp:4:7: note: candidate: ‘custom_priority_queue, main():: >::custom_priority_queue(custom_priority_queue, main():: >&&)’
main.cpp:4:7: note: no known conversion for argument 1 from ‘main()::’ to ‘custom_priority_queue, main():: >&&’
CodePudding user response:
Constructors are not automatically inherited, so your class probably lacks any constructor, except the implicitly-declared ones.
You can explicitly inherit all constructors of the base class:
template<typename T, class Container=std::vector<T>, class Compare=std::less<typename Container::value_type>>
class custom_priority_queue : public std::priority_queue<T, Container, Compare>
{
// inherit constructors
using priority_queue::priority_queue;
public:
// My additional functions here.
};