日期:2014-05-16  浏览次数:20702 次

请问如果我想利用stl::map重新生成一个类,下面的写法为什么出错
safe_map.h

#ifndef SAFE_MAP_H
#define SAFE_MAP_H

#include <map>

using namespace std;

template <class _Key, class _Tp, class _Compare = less<_Key>,
  class _Alloc = allocator<pair<const _Key, _Tp> > >
class safe_map:public std::map{

};

#endif

testpro.cpp
#include "safe_map.h"
#include <map>

int main()
{
safe_map<int,int> sm;

sm.insert(safe_map<int,int>::value_type(3,3));

for(safe_map<int,int>::iterator it=sm.begin();it!=sm.end();it++)
{
cout<<it->first<<","<<it->second<<endl;
}

return 0;
}

编译报错:
test.cpp: In function `int main()':
test.cpp:8: no method `safe_map<int, int, std::less<int>,
  std::allocator<std::pair<const int, int> > >::value_type'
test.cpp:10: `iterator' is not a member of type `safe_map<int, int,
  std::less<int>, std::allocator<std::pair<const int, int> > >'
test.cpp:10: syntax error before `=' token
test.cpp:10: `it' undeclared (first use this function)
test.cpp:10: (Each undeclared identifier is reported only once for each
  function it appears in.)
test.cpp:10: no matching function for call to `safe_map<int, int,
  std::less<int>, std::allocator<std::pair<const int, int> > >::end()'
test.cpp:12: `cout' undeclared (first use this function)
test.cpp:12: `endl' undeclared (first use this function)
g++: compilation of header file requested

------解决方案--------------------
首先, 最好不要从标准模板库的容器类派生
另外, map的模板参数也不能丢掉了
template <class _Key, class _Tp, class _Compare = less <_Key>,
class _Alloc = allocator <pair <const _Key, _Tp> > >
class safe_map:public std::map<...>
{
这里还需要加上一堆的typedef, 比如value_type之类的
};
------解决方案--------------------
探讨
那可以派生新的模板么,如果派生模板是要把所有被派生的模版类的原有内容完全重新抄写一遍么?