首页 > 解决方案 > 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?

标签: c++visual-c++stloverloading

解决方案


在您的代码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);
        });
}

推荐阅读