title: C++ policy based design.... base class as either sigleton or not based on template parametere.
body: <p>The OutputPolicy of my class sometimes goes to a static/singleton object and sometime goes to a 1-to-1 object. </p>
  
  <p>Not sure if I can explain in english.. so here is the desired behavior in pseudo code:</p>
  
  <pre><code>template&lt; 
      class Algo,
      template&lt;class&gt; OutputPolicy
  &gt;
  class AlgoBase : Algo, OutputPolicy&lt;Algo&gt;
  {
  };
  
  class AlgoImp
  {
  public:
      AlgoImp(string topic) {} 
      void OnData(
      {
          cout &lt;&lt; " AlgoImp::OnData";
          if ( .... ) 
              NewMsg(msg);
      }
  };
  
  class AlgoImp2
  {
  public:
      AlgoImp2(string topic) {} 
      void OnData(
      {
          cout &lt;&lt; " AlgoImp2::OnData";
          if ( .... ) 
              NewMsg(msg);
      }
  };
  </code></pre>
  
  <p>AlgoImp::OnData, does some processing and calls NewMsg. I am trying to decouple the implimentation of the NewMsg() call.  </p>
  
  <pre><code>template &lt; class T&gt;
  class OutMessageQueueTcp
  {
      void NewMsg(string in)
      {
          //Should be a signgleton or static
          cout &lt;&lt; " OutMessageQueueTcp::NewMsg";
      }
  };
  </code></pre>
  
  <p>If OutputPolicy is OutMessageQueueTcp (above) then there should only be one instance of OutputPolicy. So I would either have to derive from a Singleton or use a static variable somewhere. </p>
  
  <pre><code>template &lt;class T&gt;
  class OutMessageAsInput : AlgoBase&lt;AlgoImp2, OutMessageQueueTcp&gt;
  { 
      void NewMsg(string in)
      {
          cout &lt;&lt; " OutMessageAsInput::OnData";
          AlgoBase&lt;AlgoImp2, OutMessageQueueTcp&gt;::NewMsg(in);
      }
  };
  </code></pre>
  
  <p>If OutputPolicy is OutMessageAsInput (above) then the out becomes input to a sister object and then will be sent to  OutMessageQueueTcp. </p>
  
  <p>Here is the main.</p>
  
  <pre><code>main 
  {
      AlgoBase&lt;AlgoImp, OutMessageAsInput&gt; myalgo1;
      myalgo1.OnData("hi");
  }
  </code></pre>
  
  <p>And my desired output: </p>
  
  <pre><code>AlgoImp::OnData
  OutMessageAsInput::NewMsg 
  AlgoImp2::OnData
  OutMessageQueueTcp::NewMsg
  </code></pre>
  
  <p>What I really have is a collection of AlgoImp objects, each with its own topic and data. AlgoImp will generate outout by calling NewMsg. Sometimes these messages should be sent to a Socket, and sometimes they should be processed by AlgoImp2. </p>
  
  <p>This decision will happen at compile time. There will be many Algo's each doing diff things. Seems like I am trying to do some kind of Aspect oriented stuff. </p>
  
  <p><strong>Question:</strong></p>
  
  <p><strong>Is it possible to have a Base class be either a singleton or a normal object by making it a policy? Is there a design pattern for something like this? Maybe some kind of factory?</strong> </p>
  
  <p>Thanks for the help. </p>