std::map::size_type for a map whose value type is its own size_type

  • A+
Category:Languages

I have a std::map<std::pair<std::string, std::string>, float> that is taking up too much memory, and in order to use less memory, I've decided to map the unique strings to integers (e.g., std::map<std::string, int>, where each new unique string is mapped to the current size() of the map), and use those integer value as pairwise keys to the map, (e.g., std::map<std::pair<int, int>, float>).

Instead of int, I want to use std::map::size_type:

using map_index = std::map::size_type; std::pair<map_index, map_index> key; 

Of course, this doesn't compile because I need to supply the argument list for the map:

vector.cc:14:19: error: invalid use of template-name `std::map' without an argument list  using map_index = std::map::size_type; 

And this (in theory) is what I'm trying to achieve:

using map_index = std::map<std::string, map_index>::size_type; 

which gives the following (expected) compiler error:

vector.cc:15:41: error: `map_index' was not declared in this scope  using map_index = std::map<std::string, map_index>::size_type; 

What is the proper way to get the correct std::map::size_type for a map whose value type is its own size_type?

 


Disclaimer: this solution is pretty dumb. We're just going to solve the equation by repeatedly (typically once) trying to instantiate std::map until we find one that has the requested key and its own size_type as value.

template <class T> struct identity {     using type = T; };  template <class K, class V = char> struct auto_map {     using map_type = std::map<K, V>;     using type = typename std::conditional_t<         std::is_same_v<             typename map_type::mapped_type,             typename map_type::size_type         >,         identity<map_type>,         auto_map<K, typename map_type::size_type>     >::type; };  template <class K> using auto_map_t = typename auto_map<K>::type; 

If the metafunction can't find such a map, it will either error out because type ends up defined to itself, or break the recursion limit.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: