If you know the signature of the function/functor to be passed[*], you can use std::function
. Or boost::function
if you don't have C++11. So for a comparator it would be:
void sort(std::function<bool(const Element&, const Element&)> f);
where Element
is the type of the elements of the container.
Failing that you could define a class with a virtual
compare function, and allow callers to derive from it with their own class. It's more work for callers, but that's exactly what std::function
provides: a way for callers to not have to do that.
Two warnings:
make sure there's really a good reason for the implementation of your container not to be in the header file. All of the standard containers are implemented in header files, and that mostly works OK.
make sure there's really a good reason for you to implement a
sort
function. Standard containers only havesort
functions wherestd::sort
doesn't work:std::list
andstd::forward_list
.
[*] Actually std::function
doesn't require the exact same signature. You just say the types you want to call it with and the type you want to convert the return value to. So if you call it with two int
s and the caller provides a function that takes two long
s, then that's fine. The arguments are converted just like the function call would without any std::function
.