Enforce Registration of Derived Types
<p>I have an implementation of a registrar for classes that are derived from a certain base class. The intent is to have each derived class register itself and in the process provide some information about itself, which in the example below is provided through a string.</p>

<p>What I'm missing is a way to force classes that derive from <code>Base</code> to register themselves through initializing the static member <code>reg</code>. In other words, is it possible to have the compiler somehow produce an error if a derived class doesn't define/initiatlize the static member?</p>

<pre><code>struct Registrar {
  Registrar(string type) {
    registry().push_back(type);
  }
  static vector&lt;string&gt; &amp; registry() {
    static vector&lt;string&gt; * derivedTypes = new vector&lt;string&gt;;
    return *derivedTypes;
  }
};

//CRTP
template &lt;typename Derived&gt;
class Base
{
  static Registrar reg;
};

class Derived1 : public Base&lt;Derived1&gt; {/*Class definition*/};
class Derived2 : public Base&lt;Derived2&gt; {/*Class definition*/};
class Derived3 : public Base&lt;Derived3&gt; {/*Class definition*/};
//...

//Initialize the static members of each derived type
//Commenting out any of the following 3 lines doesn't produce an error.
//Ideally, I want it to produce a compile error.
template&lt;&gt; Registrar Base&lt;Derived1&gt;::reg("Derived1");
template&lt;&gt; Registrar Base&lt;Derived2&gt;::reg("Derived2");
template&lt;&gt; Registrar Base&lt;Derived3&gt;::reg("Derived3");

int main() {

  cout &lt;&lt; "Registered Types:" &lt;&lt; endl;
  for(vector&lt;string&gt;::const_iterator it = Registrar::registry().begin();
      it != Registrar::registry().end(); ++it) {
    cout &lt;&lt; *it &lt;&lt; endl;
  }

  return 0;
}
</code></pre>
