为不区分大小写的映射定义模板
Defining a template for case-insensitive maps
目标:一个带有字符串键的std映射模板+区分大小写的可选真/假参数
它按如下方式工作,但结果很糟糕——一定有更好的方法!
//step 1: templated typdefs for case-insensitive (ci), case-sensitive (cs) maps
template <typename T> struct ci_map { typedef std::map<std::string, T, ci_compare_string> type; }; //ci version
template <typename T> struct cs_map { typedef std::map<std::string, T > type; }; //cs version
//step 2: a template specialized to select on the of the two versions
template<typename T, bool ci> struct map_choice { }; //empty decl
template<typename T> struct map_choice<T, true> { typedef ci_map<T> map_version; }; //specialize ci = true
template<typename T> struct map_choice<T, false> { typedef cs_map<T> map_version; }; //specialize ci = false
//final step, but VS 2008 compile error: 'map_choice<T,ci>::map_version::type': dependent name is not a type
template<typename T, bool ci=true>
struct mymap { typedef map_choice<T, ci>::map_version::type type; };
//too bad ... usage would have been concise ==> "mymap<int>::type mymap_instance;"
//final step: works, but ugly
template<typename T, bool ci=true>
struct mymap { typedef map_choice<T, ci> type; };
//usage (ugly !!!)
mymap<int>::type::map_version::type mymap_instance; //ouch
有什么改进的建议吗?
这个怎么样:
template <bool ci>
struct Comparator
{
typedef ci_compare_string type;
};
template<>
struct Comparator<false>
{
typedef std::less<std::string> type;
};
template <typename T, bool ci = true>
struct mymap
{
typedef std::map<std::string, T, typename Comparator<ci>::type> type;
};
template<typename T, bool ci=true>
struct mymap { typedef typename map_choice<T, ci>::map_version::type type; };
会很好用的。阅读:我必须把";模板";以及";typename";关键词?
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++ 映射的键/值的用户自定义名称?
- 定义具有非标准签名的自定义映射比较器
- 在自定义类型图中重用 SWIG 映射
- 自定义哈希表实现-将字符串映射到整数时出现内存错误
- 如何定义从函数指针到字符串的映射
- 使用自定义比较器C++映射,不插入所有元素
- 如何正确使用带有智能指针和自定义类的映射作为键和值
- C++:对象键的多映射自定义比较器
- 自定义映射类中的分段错误
- C++ 自定义映射键/值不按顺序排列
- C++ 对自定义映射迭代器函数的未定义引用
- 如何在定义映射/集合时实例化比较函数(函子)
- C++类型定义映射错误
- 如何定义映射::迭代器的列表和列表::迭代器的映射
- 如何对自定义映射进行迭代
- 在多线程应用程序中读写自定义映射时堆损坏
- 为不使用元组的自定义映射模拟std::map迭代器
- 预编译头定义映射不可用
- 定时矢量与映射与未定义映射查找