Piero V.

Heterogeneous comparisons in C++ containers

Occasionally, I still work with my Intel RealSense, on my RGBD toolbox, and affine topics.

Recently, I decided to allow multiple formats for the color images (initially, I had hardcoded them to JPEG only).

Therefore, I had to modify my data structures to work with pairs of paths instead of their common stems.

The UI to add new frames to the scene lists all the valid frames once and puts them into an ordered std::set, now keyed on the path pair.

With my previous assumption on fixed formats, I could do lookups on the set to quickly check if a provided stem was valid.

After the changes, this involved a heterogeneous comparison, i.e., a comparison of different types.

The trivial way to do this is a linear search, e.g., with std::find and a lambda or a range-based for.

However, this seemed a frequent case to me, and I was curious to see if there was a way to still take advantage of the optimized algorithms provided by the containers.

Indeed, there is! But it was added only since C++14.

After implementing bool operator<(const Other &, const Key &), you can pass std::less<> as a comparator to your container instead of the default std::less<Key>.

That is a particular template specialization that was developed for this purpose. It contains an is_transparent type that enables the templated version of some methods in STL containers.

This stack overflow answer contains many details. A TL; DR is that this implementation avoids unwanted conversions that could have undesired effects (e.g., the continuous creation of temporary objects from literals).