Ensure that a class derived from a template has a member function

I have a templated class Config<typename T, typename... U>. Now I want to make sure that all derived classes have a function void update(const T &t, U...);

I tried to do this using a virtual function, but this doesn’t work, because the T is part of the signature. So have can I force an implementation to provide that function?

Answer

As @PiotrNycz points out, a virtual function in the base class should work as follows:

template <typename T, typename ...U>
class Config
{
  virtual void update(const T &t, U...) = 0;
};

template <typename T, typename ...U>
struct UnfinishedConfig : Config<T,U...>{

};

template <typename T, typename ...U>
struct FinishedConfig : Config<T,U...>{
  void update(const T &t, U...)override{}
};


int main()
{
   FinishedConfig<int,int> c1;
#if (1)
   UnfinishedConfig<int,int> c2;  // Error!
#endif
}

Leave a Reply

Your email address will not be published. Required fields are marked *