将 typedef 与构造函数参数一起使用
Using typedef with a constructor parameter
根据我之前的问题 ,我意识到 unordered_map
的默认存储桶计数对于我的目的来说太低了。
我有一个 class 模板 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
class 构造函数来检查(dynamic_cast
?)我的 mMap
是映射还是无序映射通过使用 rehash
函数。
唯一的限制是此代码被用于数百个不能更改的地方(不能变形我的基础 class)。
由于 MapType
已经是特征 class 用于抽象 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
(忽略其中的some/all),或者让create
类的函数运行根据您的实际用例需求,在现有地图上而不是返回新地图。
根据我之前的问题 unordered_map
的默认存储桶计数对于我的目的来说太低了。
我有一个 class 模板 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
class 构造函数来检查(dynamic_cast
?)我的 mMap
是映射还是无序映射通过使用 rehash
函数。
唯一的限制是此代码被用于数百个不能更改的地方(不能变形我的基础 class)。
由于 MapType
已经是特征 class 用于抽象 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
(忽略其中的some/all),或者让create
类的函数运行根据您的实际用例需求,在现有地图上而不是返回新地图。