Last active
November 19, 2018 18:47
-
-
Save 1uc/832a62d82a97e03a9c26d92d2e683041 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#include <iostream> | |
#include <map> | |
#include <string> | |
#include <type_traits> | |
#include <utility> | |
using std::declval; | |
// check that two expression make sense: | |
// a) m[key] | |
// b) m.find(key) != m.end() | |
template < | |
class Map, class Key, | |
class SFINAE = std::void_t<decltype(declval<Map>()[declval<Key>()]), | |
decltype(declval<Map>().find(declval<Key>()) != | |
declval<Map>().end())>> | |
bool has_key(const Map &map, const Key &key) { | |
return map.find(key) != map.end(); | |
} | |
class KindOfAMap { | |
public: | |
double operator[](const std::string &key) { return 42.0; } | |
}; | |
bool has_key(const KindOfAMap &map, const std::string &key) { return true; } | |
int main() { | |
std::map<std::string, double> m; | |
m["foo"] = 32.0; | |
std::cout << has_key(m, "foo") << "\n"; | |
auto kinda_map = KindOfAMap(); | |
std::cout << has_key(kinda_map, "foo") << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment