Typedef不指定模板参数的模板类 [英] Typedef a template class without specifying the template parameters
问题描述
我试图typedef unordered_map或std :: map,取决于是否有TR1库可用。但是我不想指定模板参数。从我到目前为止,typedef的模板没有参数是不可能的,直到官方的c ++ 0x标准可用。那么任何人都知道一个优雅的解决方法吗?
I'm trying to typedef either an unordered_map or std::map depending whether there are TR1 libraries available. But I don't want to specify the template parameters. From what i've read so far, typedef'ing templates without arguments is not possible until official c++0x standard is available. So does anyone know an elegant workaround for this?
#ifdef _TR1
#include <unordered_map>
typedef std::tr1::unordered_map MyMap; //error C2976: too few template arguments
#else
#include <map>
typedef std::map MyMap; //error C2976: too few template arguments
#endif
推荐答案
我看到这样做的方式是将typedef包装在template-struct中:
The way I've seen this done is to wrap the typedef in a template-struct:
template<typename KeyType, typename MappedType>
struct myMap
{
#ifdef _TR1
typedef std::tr1::unordered_map<KeyType, MappedType> type;
#else
typedef std::map<KeyType, MappedType> type;
#endif
};
然后在您的代码中调用它:
Then in your code you invoke it like so:
myMap<key, value>::type myMapInstance;
这可能比你想要的更繁琐,但我相信它满足了C ++的当前状态。
It may be a little more verbose than what you want, but I believe it meets the need given the current state of C++.
这篇关于Typedef不指定模板参数的模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!