Home > OS >  Different amount of template variables
Different amount of template variables

Time:12-16

I have to implement a class depending on std::multiset. The idea is that when two multisets get into the same "view", my class needs to sort them, make operators and iterators, etc., but I'm stuck on basically the first step. The problem is that I'd need to create the same class, just with different amount of template variables. The main program calls my class like this, for example:

multisets_merge_view<int> mvi(a, b); //a and b are std::multiset<int>
multisets_merge_view<int, std::greater<int>> mvi(ga, gb); //ga and gb are std::multiset<int, std::greater<int>>

I need to use the g compiler with -fsanitize=address,leak,undefined -O3 -Wall -Wextra -Werror

CodePudding user response:

A pretty simple way to solve the issue would be providing a default argument for the comparator:

template <typename T, typename C = std::less<T>>
class multisets_merge_view { /* ... */ };

Since C 17 you can rely on class template argument deduction, which can simplify usage of your template class pretty much – you'd have to provide a deduction guide, though:

template <typename T, typename C>
class multisets_merge_view 
{
public:
    multisets_merge_view (std::multiset<T, C>& x, std::multiset<T, C>& y);
};

// the deduction guide:
template <typename T, typename C>
multisets_merge_view(std::multiset<T, C>& x, std::multiset<T, C>& y)
    -> multisets_merge_view <T, C>;

This allows using your class like:

multisets_merge_view mvi(a, b);
multisets_merge_view mvi_g(ga, gb);

Note: There's no need to specify any template arguments at all any more...

CodePudding user response:

can using a callback function to solve your problem, like this:

#include <functional>
#include <cmath>
typedef unsigned int uint;

template<int N>
struct IntDelay
{
   template<class OBJ, class Func>
   void setDelay(const float (&newDelays)[N], OBJ* obj, Func callback)
   {
      for (uint i = 0; i < N; i  )
         (obj->*callback)(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;

int main(){
    float delays[NUMDELAYS];
    MyDelay ins;
    ins.setDelay(delays, &ins, &MyDelay::setChanDelay);
}
  • Related