我正在设计一个自定义的 ErrorInfo 类,它可以由其他模块实现,以实现它们的特定错误信息类。错误在自定义映射中维护,其中键是由实现基类的模块定义的自定义键。键是基类的模板参数。
这是示例基类和派生类。
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
template <class K>
class ErrorInfo {
public:
ErrorInfo(){};
void setTraceAll()
{
_traceAll = true;
}
bool isSetTraceAll()
{
return _traceAll;
}
bool insert(K key, int i)
{
errorMap.insert(std::pair<K,int>(key,i));
}
bool size()
{
return errorMap.size();
}
private:
std::map<K, int> errorMap;
bool _traceAll;
};
class MyCustomKey
{
private:
int _errorCode;
public:
MyCustomKey(int errorCode): _errorCode(errorCode).
{
}
bool operator<(const MyCustomKey &rhs) const
{
return _errorCode < rhs._errorCode;
}
};
class MyCustomErrroInfo: public ErrorInfo<MyCustomKey>
{
public:
MyCustomErrroInfo(){};
};
int main(){
MyCustomErrroInfo a;
a.insert(MyCustomKey(1), 1);
a.insert(MyCustomKey(2), 2);
cout<<"Size: "<<a.size()<<endl;
}
虽然我在主函数中插入了两个不同的键,但映射的大小始终为 1。除了重载 < 运算符之外,我不确定我在这里缺少什么。对于我可能做错的任何帮助,我们将不胜感激。
最佳答案
bool size()
{
return errorMap.size();
}
如果你想得到你不应该使用 bool 的大小..
关于c++ - 以自定义类作为键的 std::map 始终返回 1 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27076187/