Skip to content

Instantly share code, notes, and snippets.

@nthery
Last active January 25, 2021 15:40
Show Gist options
  • Save nthery/b67611144d9eb9a34309b089aeb6ed8b to your computer and use it in GitHub Desktop.
Save nthery/b67611144d9eb9a34309b089aeb6ed8b to your computer and use it in GitHub Desktop.
C++14 allows to lookup into a map or set without creating a temporary key when the provided needle is convertible to the key
// See https://www.bfilipek.com/2019/05/heterogeneous-lookup-cpp14.html
#include <map>
#include <string>
std::map<std::string, int> m1;
int f1() {
// Constructs a temporary string for key.
auto it = m1.find("foo");
if (it != m1.end()) {
return it->second;
}
return 0;
}
std::map<std::string, int, std::less<>> m2;
// std::less<> enables heterogeneous lookup because it has a
// is_transparent member type which allows comparing different operands of
// different types and enables additional find() overloads.
template<class T>
constexpr bool is_heterogeneous_compare(typename T::key_compare::is_transparent*) {
return true;
}
template<class T>
constexpr bool is_heterogeneous_compare(...) {
return false;
}
static_assert(!is_heterogeneous_compare<decltype(m1)>(0));
static_assert(is_heterogeneous_compare<decltype(m2)>(0));
int f2() {
// Heterogeneous lookup: uses const char[] as key => no temporary string
auto it = m2.find("foo");
if (it != m2.end()) {
return it->second;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment