I am trying to use unordered_map. But in some of the servers we don't have tr1 library. In those cases I want to use the map. So, I want to write a header file where I will use one of the following lines.
typedef tr1::unordered_map hashmap;
typedef map hashmap;
My Problem is I am using different types of maps here.
map<string, string>
map<string, int>
map <string, map<string,int>> ..etc
If I can use the typedef to alias map or unordered_map as hashmap, then I can use the map as hashmap<string, string>
, hashmap<int, int>
in the code.
Is there any way to do this or If there is any better way please suggest me.
Thanks Vinod
Classes and structures can have nested typedefs declared within them.
Typedef allows flexibility in your class. When you want to change the data type in the program, you do not need to change multiple locations but just need to change one occurrence.
It allows efficient development without the need to incorporate or switch to C++ or languages with builtin template systems, if desired. Using generics and templates in C can also make programs more type safe, and prevent improper access of memory.
Generic functions are functions declared with one or more generic type parameters. They may be methods in a class or struct , or standalone functions. A single generic declaration implicitly declares a family of functions that differ only in the substitution of a different actual type for the generic type parameter.
You need to use a so-called metafunction for this:
template <typename Key, typename T>
struct hashmap {
typedef std::unordered_map<Key, T> type;
// or
//typedef std::map<Key, T> type;
};
Which would be used like this:
hashmap<int, float>::type some_map;
This is a very common pattern. C++0x makes this somewhat easier by providing an improved using
statement but for the moment this is the best there is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With