【问题标题】:Using static functions of a base class without specifying parameters to avoid ambiguity使用基类的静态函数而不指定参数以避免歧义
【发布时间】:2012-11-12 13:22:07
【问题描述】:

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

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

如你所见,我需要将模板参数写两次,导致代码重复。

有什么办法可以摆脱吗?

【问题讨论】:

    标签: c++ c++11 class-template


    【解决方案1】:

    你可以使用 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;
    };
    

    【讨论】:

    • IMO,非模板类最干净的解决方案。
    • using B_SBase = SBase&lt;int, double, short, .......... &gt; 是 typedef 的 C++11 替代品。
    【解决方案2】:

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

    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&lt;...&gt; 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, "");
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2015-12-13
        • 2019-09-03
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 2016-02-09
        • 1970-01-01
        • 2020-04-24
        • 2017-09-23
        相关资源
        最近更新 更多