gpt4 book ai didi

c++ - 为不区分大小写的 map 定义模板

转载 作者:搜寻专家 更新时间:2023-10-31 01:11:21 25 4
gpt4 key购买 nike

目标:带有字符串键的 std 映射模板 + 用于区分大小写的可选 true/false 参数

它按如下方式工作,但结果很难看 - 必须有更好的方法!

//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;
};

关于c++ - 为不区分大小写的 map 定义模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15002939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com