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

标签 c++ typedef metaclass

根据我之前的问题,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;
};

我想更改 Map 的默认大小,以防它是后一种类型,方法是使用其构造函数(第一个参数定义大小)或使用无序映射 rehash函数。

到目前为止,我唯一的想法是使用 Base 类构造函数来检查(dynamic_cast?)我的 mMap 是 map 还是无序映射,然后使用 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-like函数根据您的实际用例需求在现有 map 上运行,而不是返回新 map 。

关于c++ - 将 typedef 与构造函数参数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40375619/

相关文章:

c++ - C++ 列表中的段错误

c++ - 旋转功能奇怪的行为

c++ - C++的本地持续集成系统?

python - Python2/3 中 __new__ 和 __init__ 顺序的区别

c++ - QTableWidget 中的 QComboBox 和 QSpinBox 具有适当的对齐方式

c - 为什么允许多次声明 typedef 标识符?

c - 将 'typedef struct' 数组传递给函数

c - 在这种情况下如何修复 "Segmentation Fault"

python - 在Python中使用元类创建单例类

python - 是否可以使用 Python 元类反向继承?