c++ - 为什么 std::sort 找不到合适的(静态成员)函数重载?

标签 c++ visual-c++ stl overloading

<分区>

我有一个类提供可由 std::sort 使用的自定义静态比较器。以下将编译得很好(精简为最小代码示例):

#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);
}

现在,当我向 StringUtils 类添加重载时,例如

static bool customStringCompare(const char*, const char*) { return true; }

以下将起作用:

void test2()
{
    std::string s1, s2;
    StringUtils::customStringCompare(s1, s2);
}

但是,上面的 std::sort 调用会产生编译器错误 C2672(未找到匹配的重载)、C2780(预期 2 个参数 - 支持 3 个)、C2783(“_Pr”的模板参数无法找到推导)在 MSVC 2015 更新 2.

为什么 std::sort 在这种情况下找不到匹配的重载?

最佳答案

在您的代码中,std::sort 接受一个函数指针。那么编译器如何决定你想要哪个功能呢? IntelliSense 显示以下错误:

cannot determine which instance of overloaded function StringUtils::customStringCompare is intended

要使用重载,您可以将比较器转换为函数对象:

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);
        });
}

关于c++ - 为什么 std::sort 找不到合适的(静态成员)函数重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475395/

相关文章:

c++ - 以对为键访问 map

c++ - 使用 std::set 的 .begin() 和 .end() 函数会产生意想不到的结果

python - 在 Python 中乘以与 C++ 相同的精度

c++ - 向类模板特化添加方法

具有变量初始化的 C++ 构造函数

c++ - 将无效值分配给 union 中的位域

c++ - 从元组列表中访问单个元组的元素

c++ - 为什么在堆数组初始化中调用了两次复制构造函数?

c++ - 项目使用旧版本的boost库

c++ - 为什么 OPENFILENAME lpstrFileTitle 参数是 LPSTR 而不是 LPCSTR?