Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use typedef for a generic class in c++

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

like image 922
vinod Avatar asked Jun 13 '11 14:06

vinod


People also ask

Can we use typedef in class?

Classes and structures can have nested typedefs declared within them.

When should you use typedef?

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.

Do generics exist in C?

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.

What is generic function in C?

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.


1 Answers

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.

like image 191
Konrad Rudolph Avatar answered Oct 07 '22 05:10

Konrad Rudolph