Dou*_*ugN 0 c++ templates stl visual-c++
我将扩展现有的std :: map类并为其添加一个新函数:
template<typename key_type, typename value_type>
class CleanableMap : public Cleanable, public std::map<key_type, value_type>
{
CleanableMap(const CleanableMap& in); //not implemented
CleanableMap& operator=(const CleanableMap& in); //not implemented
public:
CleanableMap() {}
CleanableMap(const std::map<key_type, value_type>& in) { *this = in; }
virtual ~CleanableMap() {}
std::map<key_type, value_type>& operator=(const std::map<key_type, value_type>& in)
{
*((std::map<key_type, value_type>*)this) = in;
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
我有一个复制构造函数和赋值运算符,这样我就可以简单地将一个相同类型的现有std :: map分配给我的新映射:
CleanableMap<DWORD, DWORD> cm;
std::map<DWORD, DWORD> stdm;
cm = stdm;
Run Code Online (Sandbox Code Playgroud)
问题是,编译器抱怨一个没有意义的错误 - 我明确地编码了它抱怨的内容:
1>c:\dev\proj\commonfunc.cpp(399) : error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::map<_Kty,_Ty>' (or there is no acceptable conversion)
1> with
1> [
1> _Kty=DWORD,
1> _Ty=DWORD
1> ]
1> c:\dev\proj\templates.h(245): could be 'CleanableMap<key_type,value_type> &CleanableMap<key_type,value_type>::operator =(const CleanableMap<key_type,value_type> &)'
1> with
1> [
1> key_type=DWORD,
1> value_type=DWORD
1> ]
1> c:\dev\proj\templates.h(250): or 'std::map<_Kty,_Ty> &CleanableMap<key_type,value_type>::operator =(const std::map<_Kty,_Ty> &)'
1> with
1> [
1> _Kty=unsigned long, <--- where did it come up with that?
1> _Ty=std::pair<const DWORD,DWORD>, <--- where did it come up with that?
1> key_type=DWORD,
1> value_type=DWORD
1> ]
1> while trying to match the argument list '(CleanableMap<key_type,value_type>, std::map<_Kty,_Ty>)'
1> with
1> [
1> key_type=DWORD,
1> value_type=DWORD
1> ]
1> and
1> [
1> _Kty=DWORD,
1> _Ty=DWORD
1> ]
Run Code Online (Sandbox Code Playgroud)
在第245行可能会提到它没有意义 - 没有这样的赋值运算符(嗯,它是私有的.完全删除它不会改变任何东西).
第250行提到的'可能'是我定义的赋值运算符,但它以某种方式推导出一些其他非匹配的模板类型.它在哪里得到的?
救命!!!:)
Jar*_*Par 16
加入Neil的答案.
您不应该从std :: map派生的一个具体原因是它没有虚拟析构函数.这意味着您无法保证在通过std :: map指针破坏实现期间释放您作为地图一部分分配的任何资源.
std::map<int,int>* pMap = GetCleanableMap();
...
delete pMap; // does not call your destructor
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4097 次 |
| 最近记录: |