1

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?

Devolus
  • 21,661
  • 13
  • 66
  • 113
  • 1
    Why do you want to make sure of that? What would break if a class doesn't have such a function? How do you plan to call that function? Is `Config` using CRTP, taking the derived class as a template argument? Could you show an example of expected usage; in other words, a [mcve]? – Igor Tandetnik Mar 06 '21 at 18:25
  • 2
    There are many ways to check whether [a specific member function exists](https://stackoverflow.com/questions/257288/templated-check-for-the-existence-of-a-class-member-function), you can then use static assert to verify this. – Mansoor Mar 06 '21 at 18:26
  • Really, please confirm that you meant this code does not compile `virtual void update(const T &t, U...) = 0;` ??? – PiotrNycz Mar 06 '21 at 18:31
  • @IgorTandetnik, after thinking more about the class design, I realized that this is indeed not necessary. I wanted to have a kind of compile time check that I don't forget to implement it, but I realized, that if the function is never called, then it's maybe not needed, or the problem is not calling it, and if it is calledthen I get an error anyway. – Devolus Mar 06 '21 at 18:50

1 Answers1

0

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
}
QuatCoder
  • 232
  • 1
  • 5
  • This works. Strange, because when I tried to use the `override` keyword I got some compiler error earlier. Now this works, so maybe I did something wrong before and haven't realized it. – Devolus Mar 06 '21 at 18:56
  • @Devolus - Good point about ```override``` specifier - added . – QuatCoder Mar 06 '21 at 19:04