c++ - 以自定义类作为键的 std::map 始终返回 1 的大小

标签 c++ templates c++11 operator-overloading stdmap

我正在设计一个自定义的 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/

相关文章:

c++ - 移除模板参数包的最后一个类型

c++ - 模板代码中的类型不完整

android - Android Tensorflow Lite C++ .SO库未在运行时链接

c++ - 将一个对象与左侧的常数相乘

c++ - 我可以在 C++ 中扩展变体吗?

c++ - 在 N 元构造函数上显式?

c++ - VS2013 下的 emplace_back() 问题

c++ - GDB step over function (next) 似乎不起作用

C++ 可变参数函数 : use number of parameters as template argument

c++ - 通过 static_assert 强制执行模板类型