[英]Is there a way to have a compile time check, that all members of a class are compared within operator==
I was wondering if there is a way in C++ to have a compile time check, that verifies that all member variables of a class are compared by operator==
?我想知道 C++ 中是否有一种方法可以进行编译时检查,以验证 class 的所有成员变量是否通过
operator==
进行比较? And if there is it would also be useful to have a way to explicitly ignore this constaint on some members.如果有的话,有一种方法可以显式地忽略对某些成员的这个约束也是有用的。
This is useful for my use case in which there is a data structure that is changing over time in our development process, and it happened multiple times already that adjusting the existing operator==
was forgotten.这对于我的用例很有用,其中在我们的开发过程中有一个数据结构随着时间的推移而变化,并且已经多次发生过调整现有
operator==
的情况。 This is a silent error which results in a, let's call it "false positive behaviour", which is hard to find.这是一个无声的错误,它会导致我们称之为“误报行为”,这很难找到。
Any information is appreciated.任何信息表示赞赏。 Maybe alternative ways to solve the problem, or an explanation to why this compile time check might not be possible.
也许是解决问题的替代方法,或者解释为什么这个编译时间检查可能是不可能的。
EDIT: Sadly I am using C++17 and there is no way to update to C++20 in the near future.编辑:遗憾的是我正在使用 C++17 并且在不久的将来无法更新到 C++20。
With C++20, assuming all your class members are themselves ==
comparable, you can simply provide a defaulted definition:使用 C++20,假设所有 class 成员本身
==
可比较,您可以简单地提供默认定义:
class C {
// members
public:
bool operator==(C const&) const = default;
};
When you'll update your class, the defaulted operator will pick up on the new members automictically.当您更新 class 时,默认操作员将自动选择新成员。
As far as ignoring members in the comparison.至于忽略比较中的成员。 That's always going to be a bit involved, as defaulted operations can sometimes be.
这总是有点牵扯,因为有时可能会出现默认操作。 One approach would be to use a nested class
一种方法是使用嵌套的 class
class C {
// members
struct NoEqCompare {
mutable std::mutex mut; // A member you may want to omit.
bool operator==(NoEqCompare const&) const { return true; }
} eqIgnore;
public:
bool operator==(C const&) const = default;
};
Unlike the old trick of std::tie
-ing the members you want on a per-operator basis, this has the potential to be a bit more intractable if we need to add more operators into the mix, and then mix and match the members.与
std::tie
在每个运算符的基础上添加您想要的成员的旧技巧不同,如果我们需要将更多运算符添加到组合中,然后混合和匹配成员,这可能会更加棘手. Weigh your options.权衡您的选择。
The fundamental problem here is that you cannot iterate over class members.这里的根本问题是您不能迭代 class 成员。
The quick solution is to pack all the members which play a part in operator==
into a std::tuple
.快速的解决方案是将在
operator==
中起作用的所有成员打包到std::tuple
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.