将typedef与构造函数参数一起使用

Using typedef with a constructor parameter

本文关键字:一起 参数 构造函数 typedef      更新时间:2023-10-16

在我之前的问题"根据类模板定义类成员"之后,我意识到unordered_map的默认bucket计数对我来说太低了。

我有一个类模板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;
};

如果Map是后一种类型,我想通过使用其consturator(第一个参数定义大小(或使用无序映射rehash函数来更改其默认大小。

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

唯一的限制是,该代码在数百个地方使用,这些地方不能更改(不能多态化我的基类(。

由于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的函数在现有映射上操作,而不是返回新映射。

相关文章: