繁体   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?

这可能是一个有点愚蠢的问题,但我只需要问一下。 我试图在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类不是要继承的。

一种可能性是使用继承通过模板化的hashMap derrived类将键/值对转发到unordered_map。 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>() {} 
     //...
};

然后你可以使用hashMap作为模板,但实际上是使用unordered_map的公共接口。

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

除了前进之外,不要做任何花哨的事情,因为STL类型没有虚拟析构函数。

暂无
暂无

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

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