0

Consider the following example:

#include <string>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class foo
{
public:
    std::string name;
};

template <class T>
class handle
{
    T *p;

public:
    handle(T *t) : p(t) {}
    handle() {}
    const T &operator[](size_t i) const
    {
        return p[i];
    }
    T *operator->() const
    {
        if (p)
            return p;
        else
            return 0;
    }
};

template <class T>
bool compare(const handle<T> &x, const handle<T> &y)
{
    return x->name < y->name;
}

int main()
{
    vector<handle<foo>> vec({new foo(), new foo()});
    vec[0]->name = "efg";
    vec[1]->name = "abc";
    sort(vec.begin(), vec.end(), compare); //how to use template function pointer (unresolved becuase of template)
    for (auto i : vec)
    {
        cout << i->name << endl;
    }
}

Now what I am trying to do is to provide function pointer (predicate) for std::sort algorithm, but that predicate is made from template. But by the time of compilation, the type should be resolved, and the compiler should be able to match the range of handle<foo> againts handle<T>, where it is obvious the type of template is foo. So why am I getting error:

no matching function for call to ‘sort(std::vector<handle<foo> >::iterator, std::vector<handle<foo> >::iterator, <unresolved overloaded function type>)’

where "unresolved overloaded function type" should be resolved by time of compilation (the time when template params are resolved, so should template function).

milanHrabos
  • 2,010
  • 3
  • 11
  • 45

0 Answers0