Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding functions to typedef

I've got typedef'd two maps

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;
}

how would I be able to add a custom method to type table (lets call it createItem), so that I can do

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

I know this looks a bit overhead to do this, but I've simplified the problem. The reason for me doing this is that I still need to do something in the createItem to keep track of the insertion order of the map while maintaining the key lookup feature of a map.

like image 728
toxicate20 Avatar asked Apr 28 '26 17:04

toxicate20


1 Answers

I suppose you have ruled out a wrapper object, but it is still a valid solution.

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));
    }
    //...
};
like image 197
jxh Avatar answered Apr 30 '26 05:04

jxh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!