0

I have a producer class that stores consumers object pointers in a array of std::set under different categories in order to notify the consumers of different state data changing. std::set consumers<Consumer*>[NUM_STATE_CATEGORIES];

Because the notify logic is pretty much the same across all the different types of state data, I’d like to make a generic function to notify of the state changes, but call a different consumer function depending on the state change.

for(auto it = consumers[category1].begin(); it != consumers[category1].end(); it++)
{
(*it)->NotifyCategory1Changed(this);
}

for(auto it = consumers[category2].begin(); it != consumers[category2].end(); it++)
{
(*it)->NotifyCategory2Changed(this);
}

Is there a way to send a function pointer to a generic that will help me point to each of the consumer objects or will I need to create a container to store each function pointer?

for(auto it = consumers[category].begin(); it != consumers[category].end(); it++)
{
(*it)->GENERIC_FUNCTION_AS_PARAMETER(this);
}

Can GENERIC_FUNCTION_AS_PARAMETER be sent to point to all the saved off Consumer pointer functions of that category?

cwbusacker
  • 507
  • 2
  • 12
  • By "a generic", do you you mean a template class/function? Is there an inheritance hierarchy where using `virtual` functions would make sense? Does using `std::function` make sense? – alter_igel Apr 16 '21 at 18:12
  • Yes. These functions that I refer to are virtual as each consumer handles the state data differently. However, I want to have a generic function in the producer class call different consumer functions depending on the parameter I send in. – cwbusacker Apr 16 '21 at 18:20
  • Your question is a bit light on information. It's not really clear exactly what you have in your set, and what the different member functions would be. Also, why mix std containers and c-style arrays? Horrible style. :-) – super Apr 16 '21 at 18:21
  • This would be an interesting question if you could provide a little more informations, such as what `GENERIC_FUNCTION_AS_PARAMETER` should do, what's `this` in that context, how you manage the categories (enum, class hierarchy, ...), what data the "notify logic" needs, ... – MatG Apr 16 '21 at 18:22
  • Here is a [post](https://stackoverflow.com/questions/1087600/pointers-to-virtual-member-functions-how-does-it-work) that shows that the general idea is perfectly valid. Maybe it's enough to answer your question? Pointer-to-member-functions can also be passed as template parameters. – super Apr 16 '21 at 18:27
  • Each of these code snippets are functions in the Producer class. this is sent so the consumer may know which producer state data is changing – cwbusacker Apr 16 '21 at 18:35
  • @super what would be a better way of have a specific number of std::sets? – cwbusacker Apr 16 '21 at 23:40

0 Answers0