繁体   English   中英

为什么全球飞船运营商的行为不如预期?

[英]Why does global spaceship operator not behave as expected?

#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

为什么全球飞船运营商的行为不如预期?

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

有关libc++ 的信息,请参见此处,cppreference.com 上的编译表请参见此处。 operator<=>添加到std::forward_list的相关论文是 P1614。

如果您在此处查看 libc++ 的std::forward_list源代码,您会看到尚未提及operator<=>并且其他辅助比较运算符仍然是无条件定义的(在 C++20 中不应该是这种情况) .

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM