title: Design pattern to avoid downcasting in message passing
body: <p>Base class <code>MessageHandler</code> has derived classes. They would like to pass messages to each other. Messages could be of different classes, but can be made to share a base class. How can each <code>MessageHandler</code> avoid downcasting a received message? Is it somehow possible to do something that has the effect of template-parametrizing the virtual <code>receiveMessage</code> function on MessageHandler?</p>
  
  <p>Essentially, I'm trying to replace the following code with something that does not downcast, and is hopefully a compile-time thing:</p>
  
  <pre><code>// ...
  virtual void MessageHandler::receiveMessage(Message &amp;msg) = 0;
  // ...
  
  // to receive a message
  void DerivedMessageHandler::receiveMessage(Message&amp; msg)
  {
      switch (msg.MsgType()) // enum
      {
          case Message::MessageType::A:
              MessageA&amp; = dynamic_cast&lt;MessageA&amp;&gt;(msg);
              break;
  
          case Message::MessageType::B:
              MessageB&amp; = dynamic_cast&lt;MessageB&amp;&gt;(msg);
              break;
          default:
              // don't process unknown messages
              break;
      }
  }
  
  // to send a message
  list&lt;MessageHandler&gt; mhList;
  // populate list
  for (MessageHandler&amp; mh : mhList)
  {
      mh.receiveMessage(msg);
  }
  </code></pre>
  
  <p>I know I can't do this, but something like</p>
  
  <pre><code>template &lt;typename M&gt;
  void MessageHandler::receiveMessage(M&amp; msg) {}
  </code></pre>
  
  <p>And have each <code>DerivedMessageHandler</code> specialize on <code>M</code>? What would be a design pattern that cleanly lets each handler work on their supported message objects?</p>