tags:

views:

98

answers:

6

Is it a good idea to do the following 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.

+5  A: 

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);
Vlad
A: 

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.

peachykeen
A: 

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

Armen Tsirunyan
A: 

No problem.

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

winwaed
+1  A: 

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.

Steve Townsend
+1  A: 

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.

Valentin Heinitz