Home > Article > Backend Development > Why is std::function Not Equality Comparable?
Why Is std::function Not Equality Comparable?
Despite its widespread use, std::function is not equality comparable. This limitation, also applicable to boost::function and std::tr1::function, has its roots in language design considerations.
Originally Deleted Operators
In an early C 11 draft, the equality operators for std::function were declared as deleted, with the comment "deleted overloads close possible hole in the type system." This vague statement leaves us wondering about the nature of this "hole."
The Boolean-Like Conversion "Loophole"
According to the TR1 specification, the undeclared equality operators for std::function aim to close a loophole created by boolean-like conversions. These conversions allow function instances to be compared via == and !=.
The std::shared_ptr Exception
Unlike std::function, std::shared_ptr has well-defined equality semantics. Two pointers are considered equal if they are both empty or both non-empty and pointing to the same object. This is because std::shared_ptr's role is more straightforward and its equality semantics can be easily defined.
Complexity and Equivalence
Implementing equality comparison for std::function would require all callable types to be equality-comparable, which is not always feasible. Additionally, testing equivalence for functions can be challenging, especially when they have different argument bindings.
Conclusion
While std::function provides a convenient way to work with various callable types, its lack of equality comparability has been a deliberate design choice. Avoiding potential loopholes and accommodating the diverse nature of callable types were primary considerations behind this decision.
The above is the detailed content of Why is std::function Not Equality Comparable?. For more information, please follow other related articles on the PHP Chinese website!