问题
Comparing two instances of the following struct, I receive an error:
struct MyStruct1 {
MyStruct1(const MyStruct2 &_my_struct_2, const int _an_int = -1) :
my_struct_2(_my_struct_2),
an_int(_an_int)
{}
std::string toString() const;
MyStruct2 my_struct_2;
int an_int;
};
The error is:
error C2678: binary '==' : no operator found which takes a left-hand operand of type 'myproj::MyStruct1' (or there is no acceptable conversion)
Why?
回答1:
In C++, struct
s do not have a comparison operator generated by default. You need to write your own:
bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
return /* your comparison code goes here */
}
回答2:
As other people have said, you need to implement a comparison function yourself.
There is a proposed way to ask the compiler to generate the obvious/naive(?) implementation: see here.
It may seem a bit unhelpful of C++ not to have already Standardised this, but often structs/classes have some data members to exclude from comparison (e.g. counters, cached results, container capacity, last operation success/error code, cursors), as well as decisions to make about myriad things including but not limited to:
- which fields to compare first, e.g. comparing a particular
int
member might eliminate 99% of unequal objects very quickly, while amap<string,string>
member might often have identical entries and be relatively expensive to compare - if the values are loaded at runtime, the programmer may have insights the compiler can't possibly - in comparing strings: case sensitivity, equivalence of whitespace and separators, escaping conventions...
- precision when comparing floats/doubles
- whether NaN floating point values should be considered equal
- comparing pointers or pointed-to-data (and if the latter, how to know how whether the pointers are to arrays and of how many objects/bytes needing comparison)
- whether order matters when comparing unsorted containers (e.g.
vector
,list
), and if so whether it's ok to sort them in-place before comparing vs. using extra memory to sort temporaries each time a comparison is done - how many array elements currently hold valid values that should be compared (is there a size somewhere or a sentinel?)
- which member of a
union
to compare - normalisation: for example, date types may allow out-of-range day-of-month or month-of-year, or a rational/fraction object may have 6/8ths while another has 3/4ers, which for performance reasons they correct lazily with a separate normalisation step; you may have to decide whether to trigger a normalisation before comparison
- what to do when weak pointers aren't valid
- how to handle members and bases that don't implement
operator==
themselves (but might havecompare()
oroperator<
orstr()
or getters...) - what locks must be taken while reading/comparing data that other threads may want to update
So, it's kind of nice to have an error until you've explicitly thought about what comparison should mean for your specific structure, rather than letting it compile but not give you a meaningful result at run-time.
All that said, it'd be good if C++ let you say bool operator==() const = default;
when you'd decided a "naive" member-by-member ==
test was ok. Same for !=
. Given multiple members/bases, "default" <
, <=
, >
, and >=
implementations seem hopeless though - cascading on the basis of order of declaration's possible but very unlikely to be what's wanted, given conflicting imperatives for member ordering (bases being necessarily before members, grouping by accessibility, construction/destruction before dependent use). To be more widely useful, C++ would need a new data member/base annotation system to guide choices - that would be a great thing to have in the Standard though, ideally coupled with AST-based user-defined code generation... I expect it'll happen one day.
Typical implementation of equality operators
A plausible implementation
It's likely that a reasonable and efficient implementation would be:
inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
return lhs.my_struct2 == rhs.my_struct2 &&
lhs.an_int == rhs.an_int;
}
Note that this needs an operator==
for MyStruct2
too.
Implications of this implementation, and alternatives, are discussed under the heading Discussion of specifics of your MyStruct1 below.
A consistent approach to ==, <, > <= etc
It's easy to leverage std::tuple
's comparison operators to compare your own class instances - just use std::tie
to create tuples of references to fields in the desired order of comparison. Generalising my example from here:
inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
return std::tie(lhs.my_struct2, lhs.an_int) ==
std::tie(rhs.my_struct2, rhs.an_int);
}
inline bool operator<(const MyStruct1& lhs, const MyStruct1& rhs)
{
return std::tie(lhs.my_struct2, lhs.an_int) <
std::tie(rhs.my_struct2, rhs.an_int);
}
// ...etc...
When you "own" (i.e. can edit, a factor with corporate and 3rd party libs) the class you want to compare, and especially with C++14's preparedness to deduce function return type from the return
statement, it's often nicer to add a "tie" member function to the class you want to be able to compare:
auto tie() const { return std::tie(my_struct1, an_int); }
Then the comparisons above simplify to:
inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
return lhs.tie() == rhs.tie();
}
If you want a fuller set of comparison operators, I suggest boost operators (search for less_than_comparable
). If it's unsuitable for some reason, you may or may not like the idea of support macros (online):
#define TIED_OP(STRUCT, OP, GET_FIELDS) \
inline bool operator OP(const STRUCT& lhs, const STRUCT& rhs) \
{ \
return std::tie(GET_FIELDS(lhs)) OP std::tie(GET_FIELDS(rhs)); \
}
#define TIED_COMPARISONS(STRUCT, GET_FIELDS) \
TIED_OP(STRUCT, ==, GET_FIELDS) \
TIED_OP(STRUCT, !=, GET_FIELDS) \
TIED_OP(STRUCT, <, GET_FIELDS) \
TIED_OP(STRUCT, <=, GET_FIELDS) \
TIED_OP(STRUCT, >=, GET_FIELDS) \
TIED_OP(STRUCT, >, GET_FIELDS)
...that can then be used a la...
#define MY_STRUCT_FIELDS(X) X.my_struct2, X.an_int
TIED_COMPARISONS(MyStruct1, MY_STRUCT_FIELDS)
(C++14 member-tie version here)
Discussion of specifics of your MyStruct1
There are implications to the choice to provide a free-standing versus member operator==()
...
Freestanding implementation
You have an interesting decision to make. As your class can be implicitly constructed from a MyStruct2
, a free-standing / non-member bool operator==(const MyStruct2& lhs, const MyStruct2& rhs)
function would support...
my_MyStruct2 == my_MyStruct1
...by first creating a temporary MyStruct1
from my_myStruct2
, then doing the comparison. This would definitely leave MyStruct1::an_int
set to the constructor's default parameter value of -1
. Depending on whether you include an_int
comparison in the implementation of your operator==
, a MyStruct1
might or might not compare equal to a MyStruct2
that itself compares equal to the MyStruct1
's my_struct_2
member! Further, creating a temporary MyStruct1
can be a very inefficient operation, as it involves copying the existing my_struct2
member to a temporary, only to throw it away after the comparison. (Of course, you could prevent this implicit construction of MyStruct1
s for comparison by making that constructor explicit
or removing the default value for an_int
.)
Member implementation
If you want to avoid implicit construction of a MyStruct1
from a MyStruct2
, make the comparison operator a member function:
struct MyStruct1
{
...
bool operator==(const MyStruct1& rhs) const
{
return tie() == rhs.tie(); // or another approach as above
}
};
Note the const
keyword - only needed for the member implementation - advises the compiler that comparing objects doesn't modify them, so can be allowed on const
objects.
Comparing the visible representations
Sometimes the easiest way to get the kind of comparison you want can be...
return lhs.to_string() == rhs.to_string();
...which is often very expensive too - those string
s painfully created just to be thrown away! For types with floating point values, comparing visible representations means the number of displayed digits determines the tolerance within which nearly-equal values are treated as equal during comparison.
回答3:
You need to explicitly define operator ==
for MyStruct1
.
struct MyStruct1 {
bool operator == (const MyStruct1 &rhs) const
{ /* your logic for comparision between "*this" and "rhs" */ }
};
Now the == comparison is legal for 2 such objects.
回答4:
Starting in C++20, it should be possible to add a full set of default comparison operators (==
, <=
, etc.) to a class by declaring a default three-way comparison operator ("spaceship" operator), like this:
struct Point {
int x;
int y;
auto operator<=>(const Point&) const = default;
};
With a compliant C++20 compiler, adding that line to MyStruct1 and MyStruct2 may be enough to allow equality comparisons, assuming the definition of MyStruct2 is compatible.
回答5:
Comparison doesn't work on structs in C or C++. Compare by fields instead.
回答6:
By default structs do not have a ==
operator. You'll have to write your own implementation:
bool MyStruct1::operator==(const MyStruct1 &other) const {
... // Compare the values, and return a bool result.
}
回答7:
Out of the box, the == operator only works for primitives. To get your code to work, you need to overload the == operator for your struct.
回答8:
Because you did not write a comparison operator for your struct. The compiler does not generate it for you, so if you want comparison, you have to write it yourself.
来源:https://stackoverflow.com/questions/5740310/no-operator-found-while-comparing-structs-in-c