【问题标题】:How can I define a macro/typedef/etc for tr1::unordered_map that doesn't bind the template arguments?如何为不绑定模板参数的 tr1::unordered_map 定义宏/typedef/etc?
【发布时间】:2012-03-23 11:12:06
【问题描述】:

这可能是一个有点愚蠢的问题,但我只需要问它。我正在尝试在 C++ 中使用 unordered_map 类,但不是每次都将其引用为 tr1::unordered_map,我只想使用关键字 hashMap。我知道

typedef tr1::unordered_map<string, int> hashMap 

有效,但这种修复了键的数据类型和对应于 hashMap 的值,而我希望拥有更多类似以下的内容:

#define hashMap tr1::unordered_map

我可以根据需要定义键的数据类型和值,但这不起作用。以前有人遇到过这个问题吗?

谢谢

【问题讨论】:

    标签: c++ xcode stl hashmap unordered-map


    【解决方案1】:

    这是 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 类并不意味着继承自。

    【讨论】:

      【解决方案2】:

      一种可能性是使用继承通过模板化的 hashMap 派生类将键/值对转发到 unordered_map。即:

      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 类型没有虚拟析构函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多