这可能是个有点傻的问题,但我不得不问。我正在尝试在 C++ 中使用 unordered_map 类,但不是每次都将其作为 tr1::unordered_map 引用,我只想使用关键字 hashMap。我知道
typedef tr1::unordered_map<string, int> hashMap
有效,但这种修复了键的数据类型和对应于 hashMap 的值,而我希望有更多类似以下内容:
#define hashMap tr1::unordered_map
我可以根据需要定义键和值的数据类型,但这不起作用。以前有人遇到过这个问题吗?
谢谢
最佳答案
这是 C++11 之前的 C++ 所缺少的东西。在 C++11 中,您可以使用 template using
:
template<typename Key, typename Value>
using hashMap = tr1::unordered_map<Key, Value>;
C++03 的一个常用解决方法是创建一个带有type
成员的模板结构:
template<typename Key, typename Value>
struct hashMap {
typedef tr1::unordered_map<Key, Value> type;
};
// then:
hashMap<string, int>::type myMap;
从类继承在理论上是可能的,但通常用户会避免这样做,因为 STL 类不打算从中继承。
关于c++ - 我如何为 tr1::unordered_map 定义一个不绑定(bind)模板参数的宏/typedef/etc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9575827/