Switch statements can be lengthy, so I wrote the following class (with example usage in main()):
#include <iostream>
using namespace std;
template <typename In, typename Out, In In1, Out Out1, In In2, Out Out2, Out DefaultOut>
struct SwitchMap
{
Out operator[](const In& input) const
{
switch (input) {
case In1: return Out1;
case In2: return Out2;
default: return DefaultOut;
}
}
};
int main(int, char **)
{
SwitchMap<unsigned int, unsigned int, 3, 1, 4, 2, 3> myMap;
cout << myMap[3] << endl; // prints 1
cout << myMap[4] << endl; // prints 2
cout << myMap[5] << endl; // prints 3
return 0;
}
There are two goals I'd like to achieve:
1. I'd like to make SwitchMap accept an arbitrary number of cases (where the number of Outs is one greater than the number of Ins to provide a default return value). My example only works for two Ins, two Outs, and one default Out.
2. Is it possible to make the declaration for map
look like this: SwitchMap<3, 1, 4, 2, 3> myMap;
? It would be great if the types could be automatically deduced (although I realize this might result in the compiler choosing int
instead of unsigned int
, which I'm willing to deal with).
Can I achieve either or both of these goals?