std :: map :: size_type用于std :: map,其value_type是它自己的size_type

val*_*tis 4 c++ stl stdmap size-type c++11

我有一个std::map<std::pair<std::string, std::string>, float>占用太多内存,并且为了使用更少的内存,我决定将唯一的字符串映射到整数(例如,std::map<std::string, int>每个新的唯一字符串映射到size()地图的当前),以及使用这些整数值作为映射的成对键,(例如std::map<std::pair<int, int>, float>).

而不是int,我想使用std :: map :: size_type:

using map_index = std::map::size_type;
std::pair<map_index, map_index> key;
Run Code Online (Sandbox Code Playgroud)

当然,这不会编译,因为我需要提供地图的参数列表:

vector.cc:14:19: error: invalid use of template-name `std::map' without an argument list
 using map_index = std::map::size_type;
Run Code Online (Sandbox Code Playgroud)

而这(理论上)就是我想要实现的目标:

using map_index = std::map<std::string, map_index>::size_type;
Run Code Online (Sandbox Code Playgroud)

这给出了以下(预期)编译器错误:

vector.cc:15:41: error: `map_index' was not declared in this scope
 using map_index = std::map<std::string, map_index>::size_type;
Run Code Online (Sandbox Code Playgroud)

什么是正确的方式来让编译器推断正确value_typestd::map,其value_type是自己的size_type

fel*_*lix 5

size_t 应该对这种情况足够好.

但如果你坚持,你可以这样做:

#include <type_traits>
#include <map>

template <class Key, class Value = size_t, size_t depth = 0, class = void>
struct GetSizeType {
    using type = typename GetSizeType<Key, typename std::map<Key, Value>::size_type, depth + 1>::type;
};

template <class Key, class Value, size_t depth>
struct GetSizeType<Key, Value, depth, std::enable_if_t<std::is_same_v<Value, typename std::map<Key, Value>::size_type>>> {
    using type = typename std::map<Key, Value>::size_type;
};

template <class Key, class Value>
struct GetSizeType<Key, Value, 100, void> {};

int main() {
    using X = GetSizeType<int>::type;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它将以递归方式运行GetSizeType,递归调用将停止

  • 达到递归调用深度限制(type在这种情况下将没有成员),或
  • 找到的专业化std::map其中mapped_typesize_type是相同的(在部件type的别名size_type).

  • @ user463035818谢谢,我已删除该部分.我错误地简化了用法. (2认同)