if i have a struct with a lot of member variables.. and i have to compare between to instances. what is the best way to do that??
assuming, i have the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
struct test{
var0;
var1;
var2;
var3;
};
foo(test T0, test T1){
T0.var0 = T1.var0 ;
T0.var1 = T1.var1 ; // if i have more than 8 member variables how can i get the comparsion between both objects with less code
T0.var2 = T1.var2 ;
T0.var3 = T1.var3 ;
}
Assuming you are testing for equality (it is unclear because your function above does not return anything, and all of the code inside are assignments, not comparisons), the only way to is compare elements one by one.
However without looking I'm going to guess that boost::tie can take at most 9 parameters.
Beyond that you have to change a #define in the tuples library to increase that number.
You can overload the equality operator for your test struct. This still requires you to write the code that test all the struct members, but once that's done, you can compare any two instances of that struct the same way you would any of the basic types. ie:
1 2 3 4 5 6 7 8 9 10
struct test{
int var0;
int var1;
int var2;
int var3;
booloperator==(const test &c){ return c.var0 == var0
&& c.var1 == var1
&& c.var2 == var2
&& c.var3 == var3;}
};
With that operator defined for your struct, the following comparison is valid:
@mar11: And if you go with jRaskell's approach (which is definitely the better approach), derive privately from boost::equality_comparable to get operator!=:
Actually, i apreciate the support from @jRaskell and @jsmith very much..
But i still have some question about this topic too..
according to this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <boost/operators.hpp>
struct test : private boost::equality_comparable<test> {
int var0;
int var1;
int var2;
int var3;
booloperator==(const test &c){ return c.var0 == var0
&& c.var1 == var1
&& c.var2 == var2
&& c.var3 == var3;}
};
Do i have the possibility to check which member varaible returns false and if this is the case then i overwrite the value of the member variable from the first object??
Well, operator==, the equality comparison operator, should not do that, as it is unexpected behavior.
The answer to your question is no, but, what it sounds like is that you want to make two objects equal
to each other? ie,
a = b;
?
If so, then the above line should compile just find if 'a' and 'b' are both instances of 'test'. (The
compiler will provide you with a default assignment operator which will be sufficient for the
above structs.)