如何解决我可以在C ++中调用模板函数指针谓词吗?
请考虑以下示例:
#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 举报,一经查实,本站将立刻删除。