Often I face the problem of mapping the parameter space of one API onto the parameter space of another one. Often I see this solved by nested nested nested ... switch statements.
And I was wondering if there would happen to be a library or a technique that allows you to 'declare' the mapping instead of 'program' it.
A trivial example would consist of merging the values of two enumerates into one:
namespace sourceAPI {
struct A { typedef e { A1, A2, A3 } };
struct B { typedef e { B1, B2 } };
}
namespace targetAPI {
struct AB { typedef e { A1B1, A1B2, A2B1, A2B2, A3B1, A3B2 } };
}
In which the mapping is often done like
switch( a ){
case( A::A1 ): switch( b ) {
case( B::B1 ): return A1B1;
case( B::B2 ): return A1B2;
....
}
And this mapping still needs a 'reverse' switch, too.
But I would rather like something 'dense' like
declare( source( A::A1, B::B1 ), target( AB::A1B1 ) );
declare( source( A::A1, B::B2 ), target( AB::A1B2 ) );
....
Has anyone seen such a technique or framework or library?
You can use Boost.Bimap, which provides a bidirectional mapping between two types.
It has a bit of runtime overhead (generally, roughly the same amount of overhead you would get by using a pair of std::map
s for this purpose, which isn't a whole lot).
It does allow you to define mappings about as densely as your example, though; generally you just add pairs to the map, one pair at a time.