Я бы сделал это:
class MyClass
{
public:
void addFruit(const std::string &str, int count)
{
doToFruit(str, [&](std::vector<int> &vec){ addToVec(vec, count); });
}
void removeFruit(const std::string &str)
{
doToFruit(str, [&](std::vector<int> &vec){ removeFromVec(vec); });
}
private:
template<typename Callable>
void doToFruit(const std::string &str, const Callable &func)
{
std::pair<const char*, std::vector<int>&> fruits[] = {
{"apple", apples}, {"oranges", oranges}, {"lemons", lemons},
{"melons", melons}, {"bananas", bananas}
};
for (auto i : fruits)
if (str == i.first)
return func(i.second);
std::cout << "Unknown Fruit : " << str << '\n';
}
void addToVec(std::vector<int> &vec, int count)
{
vec.push_back(count);
}
void removeFromVec(std::vector<int> &vec)
{
vec.pop_back();
}
std::vector<int> apples;
std::vector<int> oranges;
std::vector<int> lemons;
std::vector<int> melons;
std::vector<int> bananas;
};
Вы можете использовать указатель на участников , если вы хотите повысить производительность:
class MyClass
{
public:
void addFruit(const std::string &str, int count)
{
doToFruit(str, [&](std::vector<int> &vec){ addToVec(vec, count); });
}
void removeFruit(const std::string &str)
{
doToFruit(str, [&](std::vector<int> &vec){ removeFromVec(vec); });
}
private:
template<typename Callable>
void doToFruit(const std::string &str, const Callable &func)
{
auto iFound = fruits.find(str);
if (iFound != fruits.end())
func(this->*(iFound->second));
std::cout << "Unknown Fruit : " << str << '\n';
}
void addToVec(std::vector<int> &vec, int count)
{
vec.push_back(count);
}
void removeFromVec(std::vector<int> &vec)
{
vec.pop_back();
}
std::vector<int> apples;
std::vector<int> oranges;
std::vector<int> lemons;
std::vector<int> melons;
std::vector<int> bananas;
static std::unordered_map<std::string, std::vector<int> MyClass::*> fruits;
};
std::unordered_map<std::string, std::vector<int> MyClass::*> MyClass::fruits = {
{"apple", &MyClass::apples}, {"oranges", &MyClass::oranges},
{"lemons", &MyClass::lemons}, {"melons", &MyClass::melons},
{"bananas", &MyClass::bananas}
};