首页 > 解决方案 > 根据 hash_map 键类型更改宏以选择单独的定义

问题描述

我有一个有趣的问题来处理 STL 哈希映射。

在我的代码中考虑这一点:

HSH_table(char*, obj_a) hash_1;
char* a = "abc";
char* b = "abc";

我正在 .h 文件中的某处进行 HSH_table 的 typedef。

#define HSH_table(Key, Data)  __gnu_cxx::hash_map(Key, Data)

__gnu_cxx::hash_map 的问题在于它不适用于 char*。如果两个 char* 相同(不是指针,它的值),那么它不应该插入同一个插槽。在这种情况下,a 和 b 都应该进入同一个槽,因为它们共享相同的值。那是对的吗?我看到默认行为是它在不同的插槽中插入两个指针,因为它们的指针不同。

我不想更改我的源代码,但我可以更改 .h 文件。如果我想在同一个插槽中插入,我们可能需要编写一个比较器函数。我希望比较器功能特定于一个键,即 char*。

像这样的东西:

#define HSH_table(Key, Data) \
  if (key == <char*>) { \
    __gnu_cxx::hash_map(Key, Data, Comparator) \
  else \
    __gnu_cxx::hash_map(Key, Data)

首先,可能吗?

如果是,那么我们应该写什么,以便将 char* 视为不同,而将其他所有内容视为不同。什么是正确的方式匹配 char* 这是一个宏参数。

标签: c++hashmapmacros

解决方案


您可能会使用以下内容:

template <typename Key, typename Value> struct hash_map_alias
{
    using type = std::unordered_map<Key, Value>;
};

// Provide special comparer for C-string
template <typename Value> struct hash_map_alias<const char*, Value>
{
    using type = std::unordered_map<Key, Value, StringComparer>;
};
template <typename Value> struct hash_map_alias<char*, Value>
{
    using type = std::unordered_map<Key, Value, StringComparer>;
};

// And now your MACRO
#define HSH_table(Key, Data)  typename hash_map_alias<Key, Data>::type

推荐阅读