I would like to know how to implement a template metaprogramming structure like boost::mpl::map, that is a structure that supports constant-time insertion and removal of elements, and testing for membership.
It is hard to find real implementation in boost headers behind all of workarounds, macros and generated code.
Basically, through clever use of overloading. Let's say you want to to construct a map with just two "elements":
T --> U
andX --> Y
. If we flatten out all the inheritance hierarchy, we will end up with a type that looks something like this:That way, a lookup for some key
K
would just bedecltype(map.get(K{}))
, which is compile-time constant - you don't need to walk through all the pairs to figure out there is aget(K)
. And you also have a mechanism for iterating in order, via just callingget(int_<i>{})
. Any insert/delete just creates a new map type with all the new expectedget()
functions.This isn't exactly what the code looks like, really each
get
is in its own type and the whole thing is inherited linearly up for eachpair
that you add to the map, but this is approximately what the end-goal is.It helps if you compile with
-E
and then just take a look at what gets dumped out. The key type is something calledm_item
, which defines static functions for each type of lookup. So if we want to do lookup by key, there is:Which
at
uses thusly:Where the base empty map also defines: