Uniformity of the Struct element without overloading the == operator in C ++

Is it possible to define some kind of template that can create a common comparable operator for structures?

For example, is something like this possible?

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); } 

All this makes the field a field mapping of structures. You can assume that all fields have basic types or have an overloaded operator ==.

I have many such structures, and this will save me a lot of time if I can just put it in a template or something for comparison, and not define the == operator for each individual structure. Thanks!

Update

This seems to be impossible with C ++. I wonder why this is rejected from C ++ suggestions, if anyone has a reason, let us know!

For a solution that works with basic types, only see the solution from R Sahu.

+6
source share
3 answers

Is it possible to define some kind of template that can create a common comparable operator for structures?

If the struct is indented, you can use:

 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_; }; 

Even better, you can use a function template.

 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); } 

If a struct has any addition, there is no guarantee that using std::memcmp will work to compare two objects.

+1
source

Take a look at https://github.com/apolukhin/magic_get . This library can automatically generate comparison operators for some fairly simple structures.

 #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) ? "==" : "!=") << " s2\n"; std::cout << "s1 " << ((s1 == s3) ? "==" : "!=") << " s3\n"; } // Produces // s1 == s2 // s1 != s3 
+1
source

What you are asking to do is go through different structures and compare the participants, this is my understanding.

Structure iteration

It seems like this cannot be done with standard C ++, but this thread gives some ideas on which libraries to use.

It is not clear from your question whether all structures have the same format or not, and I assume that they do not.

0
source

Source: https://habr.com/ru/post/1013813/


All Articles