开发者

std::map with typedef type in it?

开发者 https://www.devze.com 2023-01-22 16:18 出处:网络
Is it a good idea to do the followi开发者_StackOverflowng in C++: typedef std::map<std::string, boost::any> MyVals;

Is it a good idea to do the followi开发者_StackOverflowng in C++:

typedef std::map<std::string, boost::any> MyVals;

// Is the following typedef'd type inside a map a good idea?
typedef std::map<std::string, MyVals> TagValues;  

These maps will be used a lot for sequential insertion and removal.


There is nothing bad in typedefing a type commonly used in the code.

Typedefs exist only on syntactical level, they won't make any changes in the produced code. Moreover, a well chosen name will make readability better.

Just compare

std::map<std::string, std::map<std::string, boost::any>::const_iterator it =
         tagValues.find(x);

vs.

TagValue::const_iterator it = tagValues.find(x);


There's nothing wrong with using typedefs. Good, in fact, in case you need to replace the underlying container later on.

One thing that always concerns me with nested maps is to ensure the copy construction of keys and values is efficient, or use single-instance storage (shared_ptr, for example) to obviate this. Especially if you are doing a lot of inserts/removes, the cost in housekeeping can be heavy.


It is completely valid and generally a good idea, if you want to be able to easily change the type of MyVals later on. In my opinion and from what I've heard/seen/read, this is exactly what typedefs are for.

However, and this is something to watch out for, you need to make sure you never change the typedef to something that can't be legally used in a std::map. If you do, you'll run into some issues and it may be a bit of a pain to track down where the problem is at.


What bad things do you see? I for one would definitely typedef anything that is long to type...


No problem.

STL class definitions can get complicated quickly, so it is often useful to use typedefs to define collections, iterators, etc.


Nothing wrong with typedef, but if you say, that MyVals is going to be inserted and removed much, having such a haevy data type in STL container may be slow as assignment operator is involved. I would consider wrapping MyVals in boost::shared_ptr.

0

精彩评论

暂无评论...
验证码 换一张
取 消