【问题标题】:Using typedef with a constructor parameter将 typedef 与构造函数参数一起使用
【发布时间】:2016-11-02 08:44:53
【问题描述】:

根据我之前的问题Defining a class member according to the class template,我意识到unordered_map 的默认存储桶计数对于我的目的来说太低了。

我有一个类模板Base,它将使用映射或无序映射,具体取决于模板参数:

template<class A, class B> 
class Base {
    template<class T1, class T2>
    struct MapType { typedef boost:unordered_map<...> MType; };
    template<class T2>
    struct MapType<std::string, T2> { typedef std::map<...> MType; };

    typedef typename MapType<...>::MType Map;

    Map mMap;
};

我想通过使用其构造函数(第一个参数定义大小)或使用无序映射rehash 函数来更改Map 的默认大小。

到目前为止,我唯一的想法是使用 Base 类构造函数来检查 (dynamic_cast?) 我的 mMap 是映射还是无序映射,然后使用 rehash 函数。

唯一的限制是这段代码被用于数百个不能改变的地方(不能对我的基类进行多态化)。

【问题讨论】:

    标签: c++ typedef metaclass


    【解决方案1】:

    由于MapType 已经是一个用于抽象Map(其类型)的一些方面的特征类,您可以将其扩展为抽象另一个方面(构造):

    template<class A, class B> 
    class Base {
        template<class T1, class T2>
        struct MapType {
          typedef boost:unordered_map<...> MType;
          static MType create() { return MType(BUCKET_SIZE); }
        };
    
        template<class T2>
        struct MapType<std::string, T2> {
          typedef std::map<...> MType;
          static MType create() { return MType(); }
        };
    
        typedef typename MapType<...>::MType Map;
    
        Map mMap;
    
        Base() : mMap(MapType<...>::create()) {}
    }
    

    当然,您可以将一些参数传递给create(并在一种或另一种情况下忽略部分/全部),或者让create-like 函数在现有地图上运行,而不是返回一个新的,基于您的实际用例需求。

    【讨论】:

    • 谢谢!正是我所希望的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多