使用
我无法将其编译,因为它报错:
“unresolved overloaded function type”
我可以看到使用sortPair可能会有一些歧义,但我假设编译器能够根据与向量u相关的类型来解决这个问题。是否有一种方法可以指定要使用哪个函数/方法以消除歧义?
目前,注释掉第一个sortPair函数允许代码被编译并产生正确排序的输出。当然,这是因为它不再具有二义性。
std::sort
时,我如何重载正在使用的自定义比较函数?#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
class Misc {
public:
// Comment out the next three lines to compile without problems.
static bool sortPair(const std::pair<int, int> &a, const std::pair<int, int> &b){
return a.first < b.first;
}
static bool sortPair(const std::pair<double, std::string> &a, const std::pair<double, std::string> &b){
return a.first < b.first;
}
};
int main () {
std::vector<std::pair<double, std::string> > u;
u.push_back(std::make_pair(10.0, "ten"));
u.push_back(std::make_pair(5.0, "five"));
u.push_back(std::make_pair(1.0, "one"));
std::sort(u.begin(), u.end(), Misc::sortPair);
for (unsigned int i=0; i< u.size(); i++){
std::cout << u.at(i).first << std::endl;
}
return 0;
}
我无法将其编译,因为它报错:
“unresolved overloaded function type”
我可以看到使用sortPair可能会有一些歧义,但我假设编译器能够根据与向量u相关的类型来解决这个问题。是否有一种方法可以指定要使用哪个函数/方法以消除歧义?
目前,注释掉第一个sortPair函数允许代码被编译并产生正确排序的输出。当然,这是因为它不再具有二义性。
&
。 - Joe Zstatic_cast
。 - Siyuan Ren