Dynamically register constructor methods in an AbstractFactory at compile time using C++ templates

Answer One

The general technique of deriving a class like this is the Curiously Recurring Template Pattern (CRTP):

class PingMessage: public MessageTmpl < 10, PingMessage > 

Your specific technique of using a template class’s static member initialization to register subclasses of that class is (IMO) simply brilliant, and I’ve never seen that before. A more common approach, used by unit test frameworks like UnitTest++ and Google Test, is to provide macros that declare both a class and a separate static variable initializing that class.

Answer Two

Static variables are initialized in the order listed. If you move your m_List declaration before your MessageFactory::Register calls, you should be safe. Also keep in mind that if you start declaring Message subclasses in more than one file, you’ll have to wrap m_List as a singleton and check that it’s initialized before each use, due to the C++ static initialization order fiasco.

Answer Three

C++ compilers will only instantiate template members that are actually used. Static members of template classes is not an area of C++ that I’ve used much, so I could be wrong here, but it looks like providing the constructor is enough to make the compiler think that MESSAGE_ID is used (thus ensuring that MessageFactory::Register is called).

This seems very unintuitive to me, so it may be a compiler bug. (I was testing this in g++ 4.3.2; I’m curious to know how Comeau C++, for example, handles it.)

Explicitly instantiating MESSAGE_ID also suffices, at least in g++ 4.3.2:

template const uint16_t PingMessage::MESSAGE_ID;

But that’s even more unnecessary work than providing an empty default constructor.

I can’t think of a good solution using your current approach; I’d personally be tempted to switch to a technique (such as macros or using a script to generate part of your source files) that relied less on advanced C++. (A script would have the added advantage of easing maintenance of MESSAGE_IDs.)

In response to your comments:

Singletons are generally to be avoided because they’re often overused as poorly disguised global variables. There are a few times, however, when you really do need a global variable, and a global registry of available Message subclasses is one of those times.

Yes, the code that you provided is initializing MESSAGE_ID, but I was talking about explicitly instantiating each subclass’s instance of MESSAGE_ID. Explicit instantiation refers to instructing the compiler to instantiate a template even if it thinks that that template instance won’t otherwise be used.

I suspect that the static function with the volatile assignment is there to trick or force the compiler into generating the MESSAGE_ID assignment (to get around the problems that dash-tom-bang and I pointed out with the compiler or linker dropping or not instantiating the assignment).

Leave a Comment