【问题标题】:Change the macros to pick separate definition according to hash_map key type根据 hash_map 键类型更改宏以选择单独的定义
【发布时间】:2026-01-26 22:40:01
【问题描述】:

我有一个有趣的问题要处理 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* 这是一个宏参数。

【问题讨论】:

  • 首先,STL 不是C++ standard library。其次,为什么要使用不可移植的__gnu_cxx::hash_map而不是std::unordered_map,这是一个散列关联容器。
  • 至于key指针的问题,对于通常使用std::string作为key来解决的字符串。
  • 我根本看不懂那段代码。模板什么时候变成了宏?
  • 换句话说,将hash_1声明为std::unordered_map&lt;std::string, obj_a&gt;

标签: c++ hashmap macros


【解决方案1】:

您可以使用以下内容:

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

【讨论】: