C2676
Visual C++ Programming Language
Severity: MinorWhat it means
C2676 means you applied a binary operator such as +, -, ==, or < to a class or struct that has not defined that operator.
The message reads: C2676: binary 'operator': 'type' does not define this operator or a conversion to a type acceptable to the predefined operator.
The fix is to add an operator overload to the class, or compare individual members instead of the whole object.
Affected Models
- Visual Studio 2015–2022
- MSVC v14.x / v17.x
Common Causes
- Comparing two class objects with == when the class does not define operator==
- Using + or - on a class that does not define those arithmetic operators
- Attempting to sort a container of objects without defining operator<
- Assigning with += on a type that defines operator+ but not operator+=
How to Fix It
-
Add the missing operator overload to your class definition. For equality comparison, add a bool operator==(const MyClass& other) const member with the comparison logic inside.
In C++20 you can define operator== and the compiler generates operator!= automatically.
In earlier standards you must define both separately. -
If you only need ordering for standard containers (std::map, std::set), define operator< rather than operator==, since ordered containers use less-than comparisons.
std::map and std::set require operator< or a custom comparator.
std::unordered_map requires operator== and a hash function. -
For simple structs, consider comparing individual members instead of the whole object. This avoids the need for operator overloads and is often more readable.
Operator overloads are most useful when a type is compared frequently throughout the codebase.
For one-off comparisons, member-by-member comparison is clearer.
Frequently Asked Questions
Why does C2676 appear when using std::sort or std::find?
std::sort requires operator< to order elements.
std::find uses operator== to compare elements.
If your element type does not define these operators, the template instantiation fails with C2676.
Define the required operator for your type or pass a custom comparator lambda.