Search code examples
c++templatescontainerssfinae

Detect whether type is associative container


I'm writing some container manipulation functions. It is often the case that there's one version for things like vector-like containers such as vector, list, deque, array, etc. and another version for associative containers like map, multimap, unordered_map, etc. I was wondering what is the "best way" to detect whether a class is an associative container. Maybe something like detecting the existence of the mapped_type typedef with BOOST_MPL_HAS_XXX_TRAIT_DEF?


Solution

  • It's a compile time test, so there's no CPU/memory efficiency aspect to select the "best way". If you have it working by checking mapped_type with boost, and that suits your needs, there's no reason to look for anything different, though there are certainly boost-free alternatives (e.g. see here)

    Note though that set and unordered_set are deemed associative containers by the Standard, but do not have a mapped_type member - if you want to include them you could test for key_type.