c++ - Why does std::sort fail to find the appropriate (static member) function overload?
问题描述
I have a class which offers custom static comparators which can be used by std::sort
. The following would compile just fine (stripped down to a minimal code example):
#include <vector>
#include <string>
#include <algorithm>
class StringUtils
{
public:
static bool customStringCompare(const std::string&, const std::string&) { return true; }
};
void test()
{
std::vector<std::string> testList;
std::sort(testList.begin(), testList.end(), StringUtils::customStringCompare);
}
Now, when I add an overload to the StringUtils class like
static bool customStringCompare(const char*, const char*) { return true; }
the following would work:
void test2()
{
std::string s1, s2;
StringUtils::customStringCompare(s1, s2);
}
However, the std::sort
call above produces compiler error C2672 (No matching overload found), C2780 (expected 2 arguments - 3 supported), C2783 (template argument for "_Pr" could not be deduced) in MSVC 2015 Update 2.
Why does std::sort
fail to find the matching overload in this case?
解决方案
在您的代码std::sort
中采用函数指针。那么编译器如何决定你想要哪个函数呢?IntelliSense 显示以下错误:
无法确定要使用哪个重载函数
StringUtils::customStringCompare
实例
要使用重载,您可以将比较器转换为函数对象:
struct Comparator {
bool operator()(const std::string&, const std::string&) const {
return true;
}
bool operator()(const char*, const char*) const {
return true;
}
};
void test() {
std::vector<std::string> testList;
std::sort(testList.begin(), testList.end(), Comparator{});
}
或者,从 C++14 开始,您可以使用通用 lambda 函数:
void test() {
std::vector<std::string> testList;
std::sort(testList.begin(), testList.end(),
[](const auto& s1, const auto& s2) {
return StringUtils::customStringCompare(s1, s2);
});
}
推荐阅读
- git - 关闭 VS2017 后,我在多个 repos 中的 csproj.user 文件经常损坏。这是怎么回事?
- python - 从支持向量机返回最佳支持向量
- typescript - Angular 6 - 在列表中搜索复杂对象并从查找表中获取名称
- tmux - 如何激活同步窗格的键盘快捷键?
- swift - 城市名称验证正则表达式 Swift 4
- python - 从谷歌搜索结果中提取评分
- git - 如何通过将所有文件标记为“已解决”来继续进行 git 合并?
- javascript - 从顶部和底部打开一个 div
- reactjs - 将 React 组件作为道具传递
- html - document.getElementById 不工作取决于我何时放置我正在访问的 div