c++ - 专门化 hashmap 模板

标签 c++ templates hash hashmap std

我在 C++ 中使用 hash_map 并想为其提供一个简化的类型名称:

key 类型和哈希函数始终相同。

stdext::hash_map<std::string, [MAPPED TYPE], CStringHasher>

但是,我真的不想每次声明一个将字符串映射到类型 X 的 HashMap 时都写这些。

  • 我可以编写一个模板或宏来简化这个吗?

所以上面的声明看起来像:

template<typename T> StringHashmap = stdext::hash_map<std::string, T, CStringHasher>

StringHashmap<int> mapA; //Maps std::string to int
StringHashamp<bool> mapB; //Maps std::string to bool

最佳答案

正如其他人所说,如果您可以使用 C++0x,则模板别名是可行的方法:

template < typename MappedType >
using StringHashMap = stdext::hash_map< std::string, MappedType, CStringHasher >;

StringHashMap< int > mapA;
StringHashMap< bool > mapB;

(正如@MSalters 指出的那样,如果您有可用的 C++0x,您可能应该使用 std::unordered_map。)

否则,您仍然可以使用通常的解决方法,即定义一个包含 typedef 的类模板:

template < typename MappedType >
struct StringHashMap
{
    typedef stdext::hash_map< std::string, MappedType, CStringHasher > type;
};

StringHashMap< int >::type mapA;
StringHashMap< bool >::type mapB;

此解决方案的一个缺点(在 SO 上产生了许多问题)是您有时需要前缀 StringHashMap< T >::type通过 typename关键字,以便向编译器断言此名称有效地表示一种类型。这个回答我就不多说了,大家可以看看this FAQ ,尤其是接受的答案,以获取更多信息。 (感谢@sbi 提出此事。)

关于c++ - 专门化 hashmap 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4967401/

相关文章:

c++ - 如何使用 Boost.Graph 从特定节点遍历图分支?

c++ - 使用箭头符号打印圆圈

c++ - 选择一个STL容器来存储线程

.net - SHA512Managed 是否被认为是 .NET 3.5 中最好的单向哈希以确保安全?

python - 通过 Python 对 MySQL 数据库中的密码进行 SHA512 哈希处理

c++ - 图形时间线创建用于分析多线程 C++ 程序的软件 API

c++ - 远程使用 C++ 模板函数

c++ - 具有类型和模板模板参数的模板类中类型参数的部分特化

templates - Resharper 6.0 模板编辑器不再工作

javascript - 散列 JavaScript 对象