5

我的一些基类有很多参数。现在我想指定使用哪个静态函数:

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;
};

如您所见,我需要编写两次模板参数,这会导致代码重复。

有没有办法摆脱它?

4

3 回答 3

3

您可以使用 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;
};
于 2012-11-24T13:34:20.067 回答
1

如果 B 已经是一个模板(这在我的代码中主要是这种情况),那么你可以像这样使用 sth:

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

但是,如果不是,那么我知道不可能不重复基类或使用typedef SBase<...> Bs_Base. 但如果你很聪明,你只需要写两次:

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, "");
于 2012-11-24T13:39:32.847 回答
0

制作B班级模板。在那里,没有重复:

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();
}
于 2012-11-24T13:33:02.220 回答