c++ - 向 typedef 添加函数

标签 c++ function dictionary typedef

我有两个 typedef 映射

typedef std::map<std::string, std::map<std::string, migrationObj> > table;
typedef std::map<std::string, migrationObj> obj;

int main (int argc, char ** argv) {
   table t;
   t["test"].insert(obj::value_type("testID", 1));
   return 0;
}

我怎样才能添加自定义方法来键入 table(我们称之为 createItem),这样我就可以做

t["test"].createItem("testID", 1);

我知道这样做看起来有点开销,但我已经简化了问题。我这样做的原因是我仍然需要在 createItem 中做一些事情来跟踪 map 的插入顺序,同时保持 map 的关键查找功能。

最佳答案

我想您已经排除了包装器对象,但它仍然是一个有效的解决方案。

class obj {
    typedef std::map<std::string, migrationObj> maptype;
    maptype m_;
public:
    maptype * operator -> () { return &m_; }
    const maptype * operator -> () const { return &m_; }
    maptype & map () { return m_; }
    const maptype & map () const { return m_; }
    void createItem (std::string key, int value) {
        // ... your custom code ...
        m_.insert(maptype::value_type(key, value));
    }
    //...
};

关于c++ - 向 typedef 添加函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16822192/

相关文章:

C++ : Function return String in Static Library give Error : expected '=' , ',' , ';' , 'asm' 或 '__attribute__' token 之前的 ':'

c++ - 不使用临时文件读取linux命令的输出

c - "What is wrong with the following listing?"我正在尝试学习函数但需要一些帮助

javascript - 使局部函数成为全局函数

typescript - 映射类型化对象的问题 |无法调用类型缺少调用签名的表达式

haskell - 对元组内的两个列表中的对应对求和 - 在 Haskell 中

c++ - 是否可以使用另一个 cpp 文件中定义的类而不是任何 header ?

c++通过使用旧 vector 进行预排序来改进 vector 排序

c++ - Linux C++编程:Why is the connection is . so,生成的可执行依赖库为.so.version

c++ - 制作字典图的有效方法