#include <iostream>
#include <any>
#include <vector>
#include <map>
#include <unordered_map>
#include <string>
using namespace std;
// enable_if_t = MapType implements .find(KeyType key), .begin(), .end(), and .begin()
// and MapType::iterator it has it->first and it->second
template<typename MapType>
decltype(declval<MapType>().begin()->second) MapGetOrDefault(
MapType mymap,
decltype(declval<MapType>().begin()->first) key,
decltype(declval<MapType>().begin()->second) defaultValue = decltype(declval<MapType>().begin()->second){}
)
{
auto it = mymap.find(key);
if (it!=mymap.end()) return it->second;
else return defaultValue;
}
int main()
{
map<string, int> a;
unordered_map<int, string> b;
a["1"] = 2;
cout << MapGetOrDefault(a, "1") << " " << MapGetOrDefault(a, "2") << " " << MapGetOrDefault(a, "2", -1) << "\n";
b[1] = "hello";
cout << MapGetOrDefault(b, 1) << " " << MapGetOrDefault(b, 2) << " " << MapGetOrDefault(b, 3, "world") << "\n";
return 0;
}
I'm trying to make a generic get_or_default() function that can be used with all types of map. There are 4 conditions that a class must meet to be counted as map, like shown in the code comment.
How can I do this using C++ type traits? Also, how to change decltype(declval<MapType>().begin()->first) into something more clean?
Edit: is enable_if_t even needed in this case? My goal is to just prevent compilation