在创建代码时common for set
, unordered_set
, map
, and unordered_map
,我需要几种方法,其中处理实际上是不同的。我的问题是让编译器推断出要使用哪个实现。
考虑这个例子:
#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;
}
尽管 cat-line 可以工作,但 wallaby-line 会从编译器中触发以下错误 (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 */
该错误很明显,quiet
,这是一个unordered_set
,被路由到插入实现map
也是——而不是为unordered_set
.
现在,这并非完全没有希望——如果我:
- 拼出all模板参数——包括可选参数(比较器、分配器等)
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)
- 更换
unordered_set
with set
.
程序将按预期编译并工作——编译器将区分set
from map
按每个模板采用的参数数量(三对四)。
But unordered_set
具有相同数量的参数map
(四)...还有unordered_map
has five参数,所以它不会被路由到地图处理方法......
如何加强集合处理函数的声明以使其处理两种类型的集合?
我该如何处理两者map
s and unordered_map
在相同的代码中?