I have a class that contains several vectors of unrelated classes.
class Class0 {};
class Class1 {};
class Class2 {};
enum class RemoveFromVector : uint8_t { CLASS0 = 0, CLASS1 = 1, CLASS2 = 2 };
class C
{
public:
std::vector<Class0> c0s;
std::vector<Class1> c1s;
std::vector<Class2> c2s;
void RemoveFromVector(const RemoveFromVector RFV, const int Index)
{
// I'd like to replace this switch with something that's compile-time
switch ((uint8_t)RFV)
{
case 0: c0s.erase(c0s.begin() + Index); break;
case 1: c1s.erase(c1s.begin() + Index); break;
case 2: c2s.erase(c2s.begin() + Index); break;
default: break;
}
}
};
int main()
{
C c;
c.c0s.push_back(Class0());
c.c1s.push_back(Class1());
c.c1s.push_back(Class1());
c.c1s.push_back(Class1());
c.c2s.push_back(Class2());
// this should remove the last element from C.c1s
c.RemoveFromVector(RemoveFromVector::CLASS1, 2);
}
How would I write a function that removes an element from one of the vectors based on an enum (or int
) at runtime without having to write a switch that's got a case for every single vector?
In other words, I'm looking for a way to deduce which vector to call erase()
on statically at compile-time, which I then call at runtime. The correct term might be "static dispatch" though I'm not entirely certain.