Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to make a factory in C++ that complies with the open/closed principle?
    primarykey
    data
    text
    <p>In a project I'm working on in C++, I need to create objects for messages as they come in over the wire. I'm currently using the <a href="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12" rel="nofollow noreferrer">factory method pattern</a> to hide the creation of objects:</p> <pre><code>// very psuedo-codey Message* MessageFactory::CreateMessage(InputStream&amp; stream) { char header = stream.ReadByte(); switch (header) { case MessageOne::Header: return new MessageOne(stream); case MessageTwo::Header: return new MessageTwo(stream); // etc. } } </code></pre> <p>The problem I have with this is that I'm lazy and don't like writing the names of the classes in two places! </p> <p>In C# I would do this with some reflection on first use of the factory (bonus question: that's an OK use of reflection, right?) but since C++ lacks reflection, this is off the table. I thought about using a registry of some sort so that the messages would register themselves with the factory at startup, but this is hampered by the <a href="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12" rel="nofollow noreferrer">non-deterministic (or at least implementation-specific) static initialization order problem</a>. </p> <p>So the question is, is it possible to implement this type of factory in C++ while respecting the open/closed principle, and how?</p> <p>EDIT: Apparently I'm overthinking this. I intended this question to be a "how would you do this in C++" since it's really easy to do with reflection in other languages. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload