map 和 multimap 之间的 C++ 模板特化

C++ template specialization between map and multimap

在这里阅读其他主题,我已经编写了检测 class 是否为关联容器 [1] 的代码。现在为了使用 equal_range 我需要检测它是法线贴图还是多重贴图。有什么方法可以实现我的目标吗?

您可能会添加自己的类型特征:

template<typename>
struct is_map : std::false_type {};

template<typename K, typename V>
struct is_map<std::map<K, V>> : std::true_type {};

WANDBOX 例子

您还可以使用 the suggestions in this post 根据 at()operator[]

的存在进行专业化

原始答案非常适合检查类型是否为映射。但是,它不适用于测试类型是否继承自映射。我对通用解决方案进行了各种尝试,最后想出了以下代码:

namespace details {
    constexpr bool is_map(const void*) {
        return false;
    }

    template<typename K, typename V, typename Comp, typename Alloc>
    constexpr bool is_map(const std::map<K, V, Comp, Alloc>*) {
        return true;
    }
}

template<typename T>
constexpr bool is_map_v = details::is_map(static_cast<const T*>(nullptr));

using map1 = std::map<int, int>;
static_assert(is_map_v<map1>);

struct MyMap : public std::map<int, int>{};
static_assert(is_map_v<MyMap>);

static_assert(is_map_v<int> == false);

is_map 函数有 2 个重载。一个匹配指向地图的指针,另一个匹配其他所有内容。因为他们接受指针,所以传递从 map 公开派生的东西的地址也将被接受。

is_map(const void *) 仅在 T 不可能是映射时才会匹配。