c++ - 不能对 std::set<std::string, std::less<>> 使用用户提供的比较函数

标签 c++ compiler-errors stl

我偶然发现了关于 std::set 的非常奇怪的编译错误在 std::less 的帮助下使用透明比较器.考虑这个简单的程序:

using Key = std::string;

bool operator<(const Key&, int) { return true; }
bool operator<(int, const Key&) { return true; }

int main()
{
  std::set<Key, std::less<>> s;
  int x;
  auto it = s.find(x);
}

它给我编译错误:

error: no matching function for call to object of type 'const std::less<void>'
      if (__j != end() && _M_impl._M_key_compare(__k, _S_key(__j._M_node)))
                          ^~~~~~~~~~~~~~~~~~~~~~

如果我使用自己的类而不是 std::string作为 key ,它工作正常:

struct My {};
bool operator<(const My&, const My&) { return true; }

using Key = My;

为什么它不适用于 std::string

在此处查看演示:https://gcc.godbolt.org/z/MY-Y2s

UPD

我真正想做的是在 std::unique_ptr<T> 之间声明比较运算符和 T* .但我认为 std::string 会更清楚.

最佳答案

Argument-dependent lookup这是一个有趣的老东西,不是吗?

已经存在一个operator<关于 std::string在命名空间 std , 这是在寻找 < 时发现的这符合你的论点。也许与直觉相反(但并非没有充分的理由),在那之后不再尝试进一步查找!不搜索其他命名空间。即使只有您的重载实际上匹配两个参数。您的全局operator<在此上下文中有效隐藏,如以下可怕的示例所示:

namespace N
{
    struct Foo {};

    bool operator<(Foo, Foo) { return false; }
}

bool operator<(N::Foo, int) { return false; }

namespace N
{
    template <typename T1, typename T2>
    bool less(T1 lhs, T2 rhs)
    {
        return lhs < rhs;
    }
}

int main()
{
    N::Foo f;
    N::less(f, 3);
}

/*
main.cpp: In instantiation of 'bool N::less(T1, T2) [with T1 = N::Foo; T2 = int]':
main.cpp:22:17:   required from here
main.cpp:15:20: error: no match for 'operator<' (operand types are 'N::Foo' and 'int')
         return lhs < rhs;
                ~~~~^~~~~
*/

( live demo )

现在,您不能向命名空间 std 添加内容,但这很好,因为如果您不重载与其他人的类型相关的运算符,它会好得多。这是在其他库执行相同操作时隐藏 ODR 错误的最快方法。

类似地,创建一个名为 Key 的东西那是实际上只是std::string伪装是意外冲突和意外行为的秘诀。

总的来说,我强烈建议您制作 Key至少是 std::string 的“强别名” ;也就是说,它自己的类型而不是简单的别名。正如您所发现的,这也解决了您的问题,因为现在 operator<和操作数类型在同一个命名空间中。

更一般地说,如果您不是真的在这里使用别名,但确实想对标准类型进行操作,那么您将回到编写一个命名的自定义比较器,它很好地隔离了新逻辑并且使用起来也很简单。缺点当然是您每次都必须“选择加入”,但我认为总体而言这是值得的。

关于c++ - 不能对 std::set<std::string, std::less<>> 使用用户提供的比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54370103/

相关文章:

c++ - 声明的允许使用上下文

c++ - 在C++ 20中按长度排序std::vector <std::string>的代码是否正确?

c++ - Qt网络请求自动添加意外问号

c++ - winsock receive() 和accept() 的问题

c++ - 有什么方法可以使用c++和wxwidget来实现类似于wpf扩展器的功能

c++ - STL Map 在搜索尝试时抛出错误

c++ - 如何避免与制造商定义的寄存器名称相同的基类名称不明确

xcode - 我的简单代码出了什么问题?

c++ - 如何使用 Luabind 和 C++ 创建 Assets 管理类?

c++ - 在 Boost zip 迭代器上使用 C++17 并行执行算法时,为什么会出现 MSVC 错误?