Transparent Comparators in C 14
C 14 introduced a significant change to associative containers, as the member function templates find, count, lower_bound, upper_bound, and equal_range now require a transparent comparator to participate in overload resolution.
Purpose of Transparent Comparators
Transparent comparators aim to solve the issue of heterogeneous lookup in associative containers. Previous to C 14, associative containers could only perform a search with a key of the exact type as the container's key. However, in many scenarios, it is desirable to allow search with keys that are convertible to the container's key type.
Example of a Transparent Comparator
The following example illustrates a transparent comparator:
template <> struct less<> { template <class T, class U> auto operator()(T&& t, U&& u) const -> decltype(std::forward<T>(t) < std::forward<U>(u)); typedef *unspecified* is_transparent; };
This comparator can be used with heterogeneous types, as it accepts any argument types and simply forwards them to the comparison operator.
Impact on Standard Containers
By default, standard containers do not use transparent comparators. However, by explicitly using std::less<> or another transparent comparator when instantiating an associative container, the new functionality can be enabled.
Solution to the Problem
Transparent comparators allow associative containers to perform a search with keys that are convertible to the container's key type. This greatly expands the flexibility and usefulness of associative containers, particularly in scenarios where heterogeneous lookup is necessary.
Conclusion
The introduction of transparent comparators in C 14 provides a powerful mechanism for heterogeneous lookup in associative containers. By utilizing transparent comparators, developers can take advantage of the flexibility and convenience they offer.
The above is the detailed content of How Do Transparent Comparators Enhance Heterogeneous Lookups in C 14 Associative Containers?. For more information, please follow other related articles on the PHP Chinese website!