如何解决由C ++ 20中的==自动生成的!=?
这是C ++ 20中的标准行为吗?我在cppreference中找不到任何有关它的信息。
我刚刚在Clang和Visual Studio上都尝试过,它可以工作,并且不会给我任何错误或警告。我还与调试器进行了检查,以查看是否正在调用operator==
!当存在operator!=
时,C ++ 20现在是否可以自动生成operator==
?它默认为健全的!(a == b)
吗?如果是这样,那么对于C ++来说真是太棒了!
解决方法
!=
是从C ++ 20中的==
自动生成的?
在C ++ 20中,这是标准行为吗?
是的。 operator!=
是在C ++ 20中由operator==
自动生成的。
此外,如果定义operator<=>
,则生成所有四个关系运算符;如果将operator<=>
定义为默认值,则生成所有比较运算符。
大多数情况下您想做什么:
struct example
{
std::string a;
int b;
auto operator<=>(const example&) const = default;
};
,
在较旧的C ++版本中,您可以使用CRTP(严格重新定义模板原则)。
这个想法是要有一个模板库,而模板参数是Derived类:
stages:
- build-all
- build
- build-async
dev-build-all:
image: python:3.7.4-alpine3.9
script:
- echo "Hello from dev-build-all. "
stage: build-all
tags:
- docker
- linux
only:
variables:
- $stage =~ /^build-all$/ && $deployment_mode =~ /^dev$/
dev-build:
image: python:3.7.4-alpine3.9
script:
- echo "Hello from dev-build. "
stage: build
tags:
- docker
- linux
needs:
- job: dev-build-all
artifacts: false
only:
variables:
- $stage =~ /^build$/ && $deployment_mode =~ /^dev$/
dev-build-async:
image: python:3.7.4-alpine3.9
script:
- echo "Hello from dev-build-async. "
stage: build-async
tags:
- docker
- linux
needs:
- job: dev-build
artifacts: true
only:
variables:
- $stage =~ /^build-async$/ && $deployment_mode =~ /^dev$/
因此,您可以像这样使用它:
template <typename Derived>
class Comparable {
public:
friend constexpr auto operator!=(const Derived &a,const Derived &b) noexcept { return !(a == b); }
friend constexpr auto operator<=(const Derived &a,const Derived &b) noexcept { return !(b < a); }
friend constexpr auto operator>(const Derived &a,const Derived &b) noexcept { return b < a; }
friend constexpr auto operator>=(const Derived &a,const Derived &b) noexcept { return !(a < b); }
};
如果仅声明struct Example : Comparable<Example> {
friend bool operator==(const Example &a,const Example &b);
friend bool operator<(const Example &a,const Example &b);
};
运算符,则会自动生成==
,并且如果同时提供!=
和<
,则将定义所有运算符: )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。