Is there an idiomatic way to convert from `void*`?

  architecture, c++, design-patterns

I keep running across a problem where some middleware is reading from some data source (usually in the form of a void pointer), and transforming it into some useful type.

The design pattern that’s always used to solve this problem resembles the following:

void process_messages(void) {
  while (true) {
    if (!message_queue.empty()) {
      msg = message_queue.pop()
      type = msg.first;
      content = msg.second;
      
      switch (type) {
        case MessageTypes::TYPE_A:
          auto typed_msg = std::static_pointer_cast<Type_A>(content);
          do_something(typed_msg);
          break;
        case MessageTypes::TYPE_B:
          auto typed_msg = std::static_pointer_cast<Type_B>(content);
          do_something(typed_msg);
          break;
        case MessageTypes::TYPE_C:
          auto typed_msg = std::static_pointer_cast<Type_C>(content);
          do_something(typed_msg);
          break;
        ...etc.
      }
    }
  }
}

Where do_something either takes another void* as an arg or possibly some interface class that all the types implement. The identical cases go on and on as there are many different types the data could be.

To me this smells because of all the duplicate code. That said, I’m not sure of a better way to convert from a void*. Additionally since I’ve seen this problem in multiple places, I was wondering if there was a idiomatic way to solve this problem in c++, or perhaps this is it and that’s why I keep seeing it?

Source: Windows Questions C++

LEAVE A COMMENT