In creating a code common for set, unordered_set, map, and unordered_map, I need the few methods, where the handling is actually different. My problem is getting the compiler to deduce, which implementation to use.
Consider the example:
#include <map>
#include <unordered_set>
#include <string>
#include <iostream>
using namespace std;
static unordered_set<string> quiet;
static map<const string, const string> noisy;
template <template <typename ...> class Set, typename K>
static void insert(Set<K> &store, const string &key, const string &)
{
cout << __PRETTY_FUNCTION__ << "(" << key << ")\n";
store.insert(key);
}
template <template <typename ...> class Map, typename K, typename V>
static void insert(Map<K, V> &store, const string &key, const string &v)
{
cout << __PRETTY_FUNCTION__ << "(" << key << ", " << v << ")\n";
store.insert(make_pair(key, v));
}
int
main(int, char **)
{
insert(noisy, "cat", "meow");
insert(quiet, "wallaby", ""); /* macropods have no vocal cords */
return 0;
}
Though the cat-line works, the wallaby-line triggers the following error from the compiler (clang-10):
t.cc:22:8: error: no matching member function for call to 'insert'
store.insert(make_pair(key, v));
~~~~~~^~~~~~
t.cc:29:2: note: in instantiation of function template specialization
'insert<unordered_set, std::__1::basic_string<char>, std::__1::hash<std::__1::basic_string<char> > >' requested here
insert(quiet, "wallaby", ""); /* macropods have no vocal cords */
The error makes it obvious, the quiet, which is an unordered_set, is routed to the insert-implementation for map too -- instead of that made for the unordered_set.
Now, this is not entirely hopeless -- if I:
- Spell out all of the template-parameters -- including the optional ones (comparator, allocator, etc.)
template <template <typename ...> class Set, typename K, typename A, typename C> static void insert(Set<K, A, C> &store, const string &key, const string &) ... template <template <typename ...> class Map, typename K, typename V, typename A, typename C> static void insert(Map<K, V, A, C> &store, const string &key, const string &v) - Replace the
unordered_setwithset.
The program will compile and work as expected -- the compiler will distinguish set from map by the number of arguments each template takes (three vs. four).
But unordered_set has the same number of arguments as map (four)... And unordered_map has five arguments, so it will not be routed to the map-handling method...
How can I tighten the set-handling function's declaration for both types of sets to be handled by it?
How can I handle both maps and unordered_maps in the same code?