我在 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/