【发布时间】:2016-10-21 11:21:01
【问题描述】:
我在这里绞尽脑汁好几个小时,但我仍然不明白为什么在尝试运行此代码时会出现错误。 一段时间后,我设法将其缩小为表达式:
pastryPrice()
这会导致问题 - 如您所见,我正在尝试为一个排序模板函数构建大量比较器
struct dialingAreaComp{
inline bool operator()(const Deliver *d1, const Deliver *d2)const {
return d1->getDialingArea() < d2->getDialingArea();
}
};
struct pastryPrice {
inline bool operator()(const Pastry *p1, const Pastry *p2)const {
return p1->getPrice() < p2->getPrice();
}
};
template<class T>
void sortCollection(T& collection)
{
if ( typeid (collection) == typeid(vector <Deliver*>))
{
sort(collection.begin(), collection.end(), dialingAreaComp());
printCollection(collection);
}
else if (typeid (collection) == typeid(vector <Pastry*>))
{
sort(collection.begin(), collection.end(), pastryPrice());
printCollection(collection);
}
else { cout << "WRONG!"; }
}
我遇到了五个错误,都是一样的:
严重性代码描述项目文件行抑制状态 错误 C2664 'bool Bakery::pastryPrice::operator ()(const Pastry *,const Pastry *) const':无法将参数 1 从 'Deliver *' 转换为 'const Pastry *' Bakery c:\program files (x86)\微软视觉工作室 14.0\vc\include\xutility 809
还有一个:
严重性代码描述项目文件行抑制状态 错误 C2056 非法表达式 Bakery c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility 809
当我去掉上面写的表达式时,代码正常工作 - 为什么我不能将两个不同的比较器传递给一个模板函数?
现在:
C2264 是一种编译器错误,在尝试向函数传递不兼容类型的参数时发生。
但是 Deliver 功能有效,当我取下 Deliver 比较器时,Pastry 也编译了...那么不兼容的类型是什么?
【问题讨论】:
-
这是因为模板是在编译时评估的,而您的
if语句是在运行时评估的。所以总是有一个函数调用不匹配。
标签: c++ templates comparator c2664