简体   繁体   English

如何为不绑定模板参数的tr1 :: unordered_map定义宏/ typedef / etc?

[英]How can I define a macro/typedef/etc for tr1::unordered_map that doesn't bind the template arguments?

This might be a little silly question, but I just have to ask it. 这可能是一个有点愚蠢的问题,但我只需要问一下。 I am trying to use the unordered_map class in C++, but instead of referencing it everytime as tr1::unordered_map, I would like to just use the keyword hashMap.I know that 我试图在C ++中使用unordered_map类,但不是每次都将它作为tr1 :: unordered_map引用,我想只使用关键字hashMap。我知道

typedef tr1::unordered_map<string, int> hashMap 

works but that kind of fixes the datatype of the key and the value corresponding to the hashMap whereas I would like to have more like the following: 但是这样可以修复键的数据类型和hashMap对应的值,而我希望有更多如下所示:

#define hashMap tr1::unordered_map

where I can just define the datatype of the key and the value depending on the the requirement, but this does not work. 我可以在哪里定义键的数据类型和值取决于要求,但这不起作用。 Did anyone face this problem before? 以前有人遇到过这个问题吗?

Thanks 谢谢

This is something that was missing from C++ before C++11. 这是C ++ 11之前C ++中缺少的东西。 In C++11, you can use template using : 在C ++ 11中,您可以使用以下template using

template<typename Key, typename Value>
using hashMap = tr1::unordered_map<Key, Value>;

A usual workaround for C++03 is to make a template structure with a type member: C ++ 03的常用解决方法是使用type成员创建模板结构:

template<typename Key, typename Value>
struct hashMap {
  typedef tr1::unordered_map<Key, Value> type;
};
// then:
hashMap<string, int>::type myMap;

Inheriting from the class is possible in theory, but usually users refrain from doing so since the STL classes weren't meant to be inherited from. 从理论上讲,从类继承是可能的,但通常用户不会这样做,因为STL类不是要继承的。

One possibility would be to use inheritance to forward the key/value pair to unordered_map through a templated hashMap derrived class. 一种可能性是使用继承通过模板化的hashMap derrived类将键/值对转发到unordered_map。 IE: IE:

template<typename key, typename value>
class hashMap : public tr1::unordered_map<key, value>
{
public:
     // Add constructors to forward to tr1::unordered_map's constructors as
     // needed
     hashMap() : tr1::unordered_map<key, value>() {} 
     //...
};

Then you can use hashMap as a template but actually be using unordered_map's public interface. 然后你可以使用hashMap作为模板,但实际上是使用unordered_map的公共接口。

hashMap<string, int> foo;
foo["bar"] = 5;

Just don't do anything fancy other than forward, as STL types don't have virtual destructors. 除了前进之外,不要做任何花哨的事情,因为STL类型没有虚拟析构函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM