如何在c中为泛型类使用typedef++

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

#0

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.

#1

C++98 and 03 don't offer support for template typedefs, but you could do that with C++0x.

In the earlier versions you can use a template struct that has a value typedef to do what you want:

template <typename T1, typename T2>
struct hashmap
{
    typedef std::map<T1, T2> type;
};

Do note that this was for illlustrative purpose and you might also need extra template parameters to cover the comparison operator and allocator.

#2

This will be possible in c++0x, but currently there's no support for aliasing unspecialized templates. See: https://en.wikipedia.org/wiki/C%2B%2B0x#Template_aliases

As a workaround, you could use a macro to stand in for the map type, i.e:

#ifdef HAVE_TR1
#include <tr1/unordered_map>
#define HASH_MAP std::tr1::unordered_map
#else
#include <map>
#define HASH_MAP std::map
#endif

On an unrelated note, I'd call the alias "ASSOC_MAP" or even just "MAP" instead of "HASH_MAP". The latter name makes it sound like you're using hashes, lulling the user into thinking that it has constant-time insertions and deletions, rather than O(log N).

推荐文章

国内IT名企的三个方面的发展共性

国内IT名企的三个方面的发展共性

推荐文章

Eucalyptus企业云计算

Eucalyptus企业云计算

推荐文章

云计算将占据IT市场

云计算将占据IT市场

推荐文章

什么是“云计算”

什么是“云计算”

推荐文章

云计算,或许可以产生一种新的商业模式

云计算,或许可以产生一种新的商业模式

推荐文章

“EMC的云”-离中国用户到底有多远?

“EMC的云”-离中国用户到底有多远?

推荐文章

报告节选3:Linux比例近半 操作系统混战虚拟化

报告节选3:Linux比例近半 操作系统混战虚拟化

推荐文章

苹果之于存储

苹果之于存储

推荐文章

关于Ubuntu的企业云(UEC)

关于Ubuntu的企业云(UEC)

推荐文章

搭建云计算平台~Eucalyptus安装日志 centos 5.3

搭建云计算平台~Eucalyptus安装日志 centos 5.3

推荐文章

云,要掷地有声!

云,要掷地有声!

推荐文章

美国政府力挺云计算,业界沸腾

美国政府力挺云计算,业界沸腾

推荐文章

云中漫步:信息安全的共同体之路

云中漫步:信息安全的共同体之路

推荐文章

热点聚焦――云计算1(基本概念与关键技术)

热点聚焦――云计算1(基本概念与关键技术)

推荐文章

EMC剑桥实验室揭牌

EMC剑桥实验室揭牌

推荐文章

比较一下SAAS、SNS、云计算和NAS

比较一下SAAS、SNS、云计算和NAS