Your concern is real, and there's no good workaround for C++11.
C++14 fixes this issue by adding a templated overload of std::map::find
— the relevant proposal is N3657. In C++14, your program would look like this:
#include
#include
#include
#include
(std::less<>
is the generalized "less-than" comparator, equivalent to operator<
. C++03 and C++11 have a broken-by-design version of this comparator that forces both arguments to be the same type. C++14 finally does it right.)
Unfortunately the Committee seems to have decided that people should go through all their C++11 code and update every container to use std::less<>
as the comparator — it doesn't just happen by default. There's no good reason for this decision; it's just The Way It Is. (See my comments above about broken-by-design. C++ has a bad habit of introducing broken versions of things before introducing the "real" versions several years later.)
For C++11, std::map::find
has only one overload (the one that takes const Key&
), so any workaround will necessarily involve changing the Key
type to be less expensive — we can't just fiddle with the comparator, because by the time execution reaches the comparator, we've already promoted find
's argument to the Key
type.
#include
#include
#include
#include