Using static functions of a base class without specifying parameters to avoid ambiguity

StackOverflow https://stackoverflow.com/questions/13541592

  •  01-12-2021
  •  | 
  •  

Frage

Some of my base classes get tons of parameters. Now I want to specify which static function to use:

template <typename... Types>
struct SBase {
    static void func() {
    }
};

struct A : public SBase<int> {
};

struct B : public A, public SBase<int, double, short,
    unsigned int, float, unsigned char, long, unsigned long> {

    // using SBase::func; // Not possible.
    // Horrible, but works.
    using SBase<int, double, short,
    unsigned int, float, unsigned char, long, unsigned long>::func;
};

Aso you can see, I need to write the template parameters twice which leads to code duplication.

Is there any way to get rid of it?

War es hilfreich?

Lösung

You could use a typedef:

typedef SBase<int, double, short, unsigned int, float, unsigned char,
      long, unsigned long> B_SBase;

struct B : public A, public B_SBase {
    using B_SBase::func;
};

Andere Tipps

If B is already a template (which is mostly the case in my code), then you could use sth like this:

template <typename MyBase = SBase<int, double, short,
                                  unsigned int, float, unsigned char,
                                  long, unsigned long> >
struct B : public A, public MyBase {
  using MyBase::func;
};

If it's not, however, there is no possibility I'm aware of not to repeat the base class or polluting the namespace with a typedef SBase<...> Bs_Base. But if you're clever, you just have to write it twice:

struct B : public A, public SBase<int, double, short,
    unsigned int, float, unsigned char, long, unsigned long> {
  typedef SBase<int, double, short, unsigned int, float,
                unsigned char, long, unsigned long> MyBase;
};
static_assert(std::is_base_of<B::MyBase, B>::value, "");

Make B a class template. There, no repetetetitions:

template<typename... Types>
struct B : public A, public SBase<Types...> {
  using SBase<Types...>::func;
};

typedef B<int, double, short, unsigned int, float, unsigned char, long, unsigned long> BB;

void foo ()
{
  BB::func();
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top