Last active
January 25, 2021 15:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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