Note that there are some explanatory texts on larger screens.

plurals
  1. POClass member variable that takes the class as a template
    primarykey
    data
    text
    <p>So, in a recent C++ project, I've implemented a packet factory-like system where each new packet class automatically registers itself using a static register. One of the packet types is as follows:</p> <pre><code>class Packet0Connect : public Packet{ public: Packet0Connect(); Packet0Connect(const std::string&amp; name, const std::string&amp; info); virtual void write(std::ostream&amp; os) const; virtual void read(std::istream&amp; is); virtual Packet* clone() const; std::string name, info; private: static const PacketRegister&lt;Packet0Connect&gt; registry; }; </code></pre> <p>Here is what PacketRegister looks like:</p> <pre><code>template&lt;class P&gt; class PacketRegister{ public: PacketRegister(){ PacketMap* packetMap = PacketManager::getPacketMap(); if(packetMap-&gt;count(prototype.packetID) == 0){ packetMap-&gt;insert(std::make_pair(prototype.packetID, (const Packet*)&amp;prototype)); } } P prototype; }; </code></pre> <p>The registry variable is properly initialized at the top of an implementation file, and in its constructor it adds a mapping to the specific packet type, in this case Packet0Connect, with its ID. I quite like that way I managed to do this, as it doesn't allocate any memory on the stack. The above compiles fine using GCC 4.2.1 on Mac OSX, however, when I tried to compile with Visual C++ 2010 on 32-bit Windows Vista, I run into this error:</p> <pre><code>error C2079: 'PacketRegister&lt;P&gt;::prototype' uses undefined class 'Packet0Connect' with [ P=Packet0Connect ] see reference to class template initialization 'PacketRegister&lt;P&gt;' being compiled with [ P=Packet0Connect ] </code></pre> <p>After doing some googling about the error, I found out that it usually gets thrown when you try to use a forward declared class as a template argument. That does make sense, because Packet0Connect isn't fully defined when the PacketRegister is, but there must be a way to make this work with VC++. I know I could just make the register a global variable after defining the class, but I would prefer not to if I can make it work as a static member variable.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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