问题描述
请考虑以下示例:
#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;
}
}
现在我要做的是为std::sort
算法提供函数指针(谓词),但是该谓词是由模板制成的。但是到编译时,类型应该已经解析,并且编译器应该能够匹配handle<foo>
范围handle<T>
的范围,显然模板的类型是foo
。那我为什么会出错:
no matching function for call to ‘sort(std::vector<handle<foo> >::iterator,std::vector<handle<foo> >::iterator,<unresolved overloaded function type>)’
其中“未解析的重载函数类型”应在编译时解决(模板参数解析的时间,模板函数也应解析)。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)