gpt4 book ai didi

c++ - 向 typedef 添加函数

转载 作者:行者123 更新时间:2023-11-30 02:54:49 24 4
gpt4 key购买 nike

我有两个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com