结构成员相等而不重载运算符== 在C++
Struct member equality without overloading operator== in C++
是否可以定义某种模板来为结构创建通用的可比较运算符?
例如,这样的事情有可能吗?
struct A
{
int one;
int two;
int three;
};
bool AreEqual()
{
A a {1,2,3};
A b {1,2,3};
return ComparableStruct<A>(a) == ComparableStruct<A>(b);
}
所有这些都是结构的逐字段比较。您可以假设所有字段都是基本类型或具有重载运算符==。
我有很多这样的结构,如果我能把它放在模板或其他东西中进行比较,而不是为每个结构定义一个运算符==,这将节省我很多时间。谢谢!
更新
这似乎C++是不可能的。我想知道为什么这在C++提案中被投票出来,如果有人有理由让我们知道!
有关适用于基本类型的解决方案,请参阅R Sahu的解决方案。
是否可以定义某种模板来为结构创建通用的可比较运算符?
如果struct
没有填充,则可以使用:
template <typename T>
struct ComparableStruct
{
ComparableStruct(T const& a) : a_(a) {}
bool operator==(ComparableStruct const& rhs) const
{
return (std::memcmp(reinterpret_cast<char const*>(&a_), reinterpret_cast<char const*>(&rhs.a_), sizeof(T)) == 0);
}
T const& a_;
};
更好的是,您可以使用函数模板。
template <typename T>
bool AreEqual(T cost& a, T const& b)
{
return (std::memcmp(reinterpret_cast<char const*>(&a), reinterpret_cast<char const*>(&b), sizeof(T)) == 0);
}
如果struct
有任何填充,则不能保证使用 std::memcmp
可以比较两个对象。
看看 https://github.com/apolukhin/magic_get。这个库可以为一些相当简单的结构自动生成比较运算符。
#include <iostream>
#include <boost/pfr/flat/global_ops.hpp>
struct S {
char c;
int i;
double d;
};
int main() {
S s1{'a', 1, 100.500};
S s2 = s1;
S s3{'a', 2, 100.500};
std::cout << "s1 " << ((s1 == s2) ? "==" : "!=") << " s2n";
std::cout << "s1 " << ((s1 == s3) ? "==" : "!=") << " s3n";
}
// Produces
// s1 == s2
// s1 != s3
你要求做的是遍历各种结构和比较成员是我的理解。
循环访问结构
这似乎不能用标准 c++ 来完成,但该线程提供了一些关于使用哪些库的想法。
从您的问题中不清楚所有结构是否具有相同的格式,我假设它们没有。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<