2

This is kind of a two-part question, but I believe they're very closely related.

Question 1:

I've read on other questions that there are ways to enforce a class in having certain static functions, like such:

class Type{
   virtual void staticVirtual() = 0;
};

template<typename T>
class StaticContract{
   void staticVirtual(){
       T::foo();
   }
};

If I made a class that inherited from this contract:

class Example : public StaticContract<Example>{
   ...
};

Then Example would have to implement a static function foo().

The problem I'm having is if I make a templated class that inherits from the contract:

template <Typename T>
class mTemplateClass : 
   public StaticContract<mTemplateClass<T>>{
   ...
}

I don't get any errors for not implementing foo().

How can I enforce a template to have certain static functions that I can call, or is that even possible?


Question 2:

Considering the above question, each StaticContract contains a static instance of a Registration that is instantiated with the type passed, (StaticContract<typename T> and will have a Registration<T>):

template <typename T>
class Registration :
    public Registrants
{
public:
    Registration() {
        vectorOfFunctions->push_back(&T::foo);
    }
};

When the class inheriting from StaticContract is not a template, this works fine, but when its a template, it'll never push back an instance of its function, not to mention it doesn't even enforce its implementation.

How can I push back this function from the most derived class?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • The issues you are having is due to the fact that when a template class is instantiated, only the parts of the class that are actually used needds to be instatiated by the compiler. I've seen people do similar things like this for automatic registration of classes, but I've never seen a clean variant that actually works. It usually involves having to declare some static variable of the class with the return-value of the registration function. – super Apr 01 '20 at 23:43
  • Does this answer your question? [How to force a static member to be initialized?](https://stackoverflow.com/questions/6420985/how-to-force-a-static-member-to-be-initialized) – Davis Herring Apr 03 '20 at 02:25
  • No, because in that question, a normal class inherits from the template, but I have a template inheriting from a template. Neither of the templates are ever initialized, they just need their functions. – Joseph Grimaldo Apr 06 '20 at 02:25

0 Answers0