0

I'm using mixins to add optional functionality to a simple base class, like so:

template<int N>
struct IntDelay
{
   void setDelay(const float (&newDelays)[N])
   {
      for (uint i = 0; i < N; i++)
         setChanDelay(newDelays[i], i);
   }

   void setChanDelay(float newDelay, uint chan)
   {
      delay[chan] = std::floor(newDelay);
   }

protected:
   float delay[N];   
};

template<int N, class BASE>
struct FloatDelay : public BASE
{
   void setChanDelay(float newDelay, uint chan)
   {
      delay[chan] = newDelay;
   } 
};

#define NUMDELAYS 4
typedef FloatDelay<NUMDELAYS, IntDelay<NUMDELAYS>> MyDelay;

When I call setDelay on a MyDelay object, this method then calls the setChanDelay method of the base IntDelay class, whereas I would like it to call the setChanDelay method of the FloatDelay class.

I think I understand why this is - the base class method setDelay doesn't know about the derived class method at all - but I'm wondering if there is some way to make it work as I want, using static inheritance like this.


EDIT: to explain why I didn't use CRTP....

In addition to the two trivial classes here there are multiple other mixin classes in this library I'm building, and the final classes (like MyDelay) will be determined on a project level. Here's a silly example to demonstrate:

template<int N, class BASE>
struct SqrtDelay: public BASE
{
   void setChanDelay(float newDelay, uint chan)
   {
      BASE::setChanDelay(std::sqrtf(newDelay), chan);
   } 
};

// Project A
typedef SqrtDelay<NUMDELAYS, IntDelay<NUMDELAYS>> MyDelay;

// Project B
typedef SqrtDelay<NUMDELAYS, FloatDelay<NUMDELAYS, IntDelay<NUMDELAYS>>> MyDelay;

I was just unable to build something open-ended and modular like this using CRTP (admittedly probably my lack of understanding).

kippertoffee
  • 101
  • 2
  • do you know about `virtual` ? – 463035818_is_not_an_ai Dec 16 '21 at 10:14
  • Yes, I'm trying to avoid using virtual functions. The reason I'm making this modular in the first place is that it's required to run on a range of hardware, scaling down to *very* limited MCUs. Every cycle counts. – kippertoffee Dec 16 '21 at 10:21
  • ok now I get it, so no virtuals, but then the next question is: Do you know [CRTP](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)? This looks almost like it, but only almost – 463035818_is_not_an_ai Dec 16 '21 at 10:47
  • Does this answer your question? https://stackoverflow.com/questions/4173254/what-is-the-curiously-recurring-template-pattern-crtp – 463035818_is_not_an_ai Dec 16 '21 at 10:48
  • I tried to formulate this using the CRTP paradigm, as I realised the bottom-up approach might fix this, but I couldn't formulate it right. I'll elaborate on that in an edit in my question.... – kippertoffee Dec 16 '21 at 11:10

0 Answers0