【问题标题】:Why does global spaceship operator not behave as expected?为什么全球飞船运营商的行为不如预期?
【发布时间】:2020-04-08 08:08:09
【问题描述】:
#include <compare>
#include <forward_list>

template<typename T>
struct A
{
    std::forward_list<T> l;
};

template<typename T>
auto operator<=>(const A<T>& lhs, const A<T>& rhs)
{
    return lhs.l <=> rhs.l;
}

int main()
{
    std::forward_list<int>{} < std::forward_list<int>{}; // ok

    A<int>{} < A<int>{}; // error
}

使用clang++ -std=c++20 -stdlib=libc++ main.cpp 和错误消息编译:

main.cpp:13:18: error: invalid operands to binary expression ('const std::forward_list<int>' and 'const std::forward_list<int>')
    return lhs.l <=> rhs.l;
           ~~~~~ ^   ~~~~~
main.cpp:20:14: note: in instantiation of function template specialization 'operator<=><int>' requested here
    A<int>{} < A<int>{}; // error

为什么全球飞船操作员的行为不符合预期?

【问题讨论】:

  • 你能让问题文本更具体到实际问题吗?什么是“不期望”?在这种情况下,问题似乎是“为什么我不能在 std::forward_list 上调用 &lt;=&gt;?”全局宇宙飞船运算符的行为似乎完全符合您的要求 - 毕竟它被调用了。

标签: c++ clang standards c++20 spaceship-operator


【解决方案1】:

libc++(或任何标准库)似乎还没有完全实现太空飞船运算符库的添加。

请参阅 here for libc++here 以获取 cppreference.com 上的编译表。将operator&lt;=&gt; 添加到std::forward_list 的相关论文是P1614。

如果你查看 libc++ 的 std::forward_list here 的源代码,你会发现还没有提到 operator&lt;=&gt; 并且其他二级比较运算符仍然是无条件定义的(在 C+ 中不应该是这种情况+20)。

std::forward_list&lt;int&gt;{} &lt; std::forward_list&lt;int&gt;{}; 编译是因为它使用operator&lt;,而不是operator&lt;=&gt;。如果您直接尝试std::forward_list&lt;int&gt;{} &lt;=&gt; std::forward_list&lt;int&gt;{},它也会失败(在当前的 libc++ 状态下)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-20
    • 2019-08-20
    • 1970-01-01
    • 2022-04-02
    • 1970-01-01
    • 2014-01-22
    • 2017-12-09
    • 2011-07-09
    相关资源
    最近更新 更多