我正在尝试创建一个将 map 作为模板参数的类。特别是它应该能够采用 std::map 和 boost::ptr_map。目前我正在尝试这个:
template <template<typename, typename> class MAP, typename KEYTYPE, typename DATATYPE>
class RestrictedMapBase
{
/* bunch of methods ... */
}
这个类被另外两个类继承,一个用于 std::map,一个用于 boost::ptr_map。
template <typename KEYTYPE, typename DATATYPE>
class RestrictedMap: public RestrictedMapBase<std::map, KEYTYPE, DATATYPE>
{
/* Bunch of methods ... */
};
template <typename KEYTYPE, typename DATATYPE>
class RestrictedPointerMap: public RestrictedMapBase<boost::ptr_map, KEYTYPE, DATATYPE>
{
/* Bunch of methods ... */
};
但是在编译时我得到了这些错误:
RestrictedMap.h(166) : error C3201: the template parameter list for class template 'std::map' does not match the template parameter list for template parameter 'MAP' RestrictedMap.h(183) : see reference to class template instantiation 'STLUtils::RestrictedMap' being compiled
RestrictedMap.h(186) : error C3201: the template parameter list for class template 'boost::ptr_map' does not match the template parameter list for template parameter 'MAP' RestrictedMap.h(203) : see reference to class template instantiation 'STLUtils::RestrictedPointerMap' being compiled
任何人都可以指出我做错事的正确方向吗?谢谢。
最佳答案
std::map 需要一个模板参数来定义它是什么的映射。见下文:
template <typename KEYTYPE, typename DATATYPE>
class RestrictedMap: public RestrictedMapBase<std::map<KEYTYPE, DATATYPE>, KEYTYPE, DATATYPE>
{
/* Bunch of methods ... */
};
您的基类模板参数 KEYTYPE
和 DATATYPE
将变得多余。您可以用 std::map 类中提供的 typedef 替换它们:
std::map<_Kty, _Ty>::key_type; // This is the same as KEYTYPE
std::map<_Kty, _Ty>::mapped_type; // This is the same as DATATYPE
我会像这样重写你的类(class)(我还没有测试过):
template <typename Map>
class RestrictedMap
{
public: // Typedefs
typedef typename Map::key_type KeyType;
typedef typename Map::mapped_type MapType;
public: // Methods
// TODO: Write your methods here.
void Add(const KeyType &key, const MapType &map);
private: // Members
Map m_map;
};
然后你可以像这样选择你的 map (同样未经测试):
typedef RestrictedMap<std::map<int, int>> StlMap; // TODO: Change your map's key and data type
typedef RestrictedMap<boost::ptr_map<int, int>> BoostMap; // TODO: Change your map's key and data type
此处提供完整示例 - http://ideone.com/U3AkV
关于c++ - 将模板类作为模板的模板类将无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10446449/