I think this question may just be more about my weakness with doing anything nontrivial with templates more than the problem itself, but I would like to implement a template class that is used like so:
MyArray<std::string, 1, 3, 7> a;
a[1] = "hello";
a[3] = "world";
a[7] = "!";
// runtime error
// a[4] = "?";
Under the hood, MyArray<std::string, 1, 3, 7>
would basically be equivalent to the following:
class C
{
private:
std::string _values[3];
public:
std::string & operator[](std::size_t index)
{
switch(index)
{
case 1: return _values[0];
case 3: return _values[1];
case 7: return _values[2];
default: /* some error condition */
}
}
};
(Of course in real life I'm more likely to use enum values than raw integers, but this gets the point across with a minimum of example code.)
Criteria:
- Needs to work if the indices aren't known at compile time
- Access should use a switch statement or something equivalent, not a runtime linear search through permitted keys.
- Don't want a hashmap with potential bucket collisions like
std::unordered_map
I'd also be happy with a reference that explains how to write this sort of template code.