The Conundrum:
Why is std::function, an integral component of modern C codebases, not endowed with equality comparison capabilities? This question has perplexed programmers since its inception, leading to confusion and difficulties in managing collections of callable objects.
The Early Ambiguity:
In an early draft of the C 11 standard, overloads for operator== and operator!= were declared but deleted, leaving a void that was never adequately explained. The accompanying comment "close possible hole in the type system" hinted at a hidden flaw, but its nature remained a mystery.
The Loophole and the Safeguard:
The suspected "loophole" stems from the presence of a boolean conversion function. In the absence of explicit equality comparison operators, this function can allow for implicit comparisons via == or !=. However, this loophole can lead to unexpected behavior, as demonstrated by:
<code class="cpp">struct S { operator bool() { return false; } }; int main() { S a, b; bool are_equal(a == b); // Uses operator bool on a and b! }</code>
C 03 introduced the safe-bool idiom and C 11 implemented an explicit bool conversion function to prevent this loophole.
The Contrast with std::shared_ptr:
Unlike std::function, std::shared_ptr has well-defined equality semantics. Two pointers are equal if they are both empty or if they are both non-empty and pointing to the same object. This clear definition allowed for the implementation of equality comparison operators in std::shared_ptr.
The Enigma Unraveled:
The rationale for not making std::function equality comparable stems from the inherent challenge of defining a meaningful equality criterion for arbitrary callable types. If enforced, it would place a burden on all function object implementers, and it could still lead to ambiguous comparisons due to differences in binding arguments. Furthermore, the absence of equality operators effectively closes the loophole that arises from implicit conversions.
The above is the detailed content of Why Does `std::function` Lack Equality Comparison?. For more information, please follow other related articles on the PHP Chinese website!