根据参数数量调用mixin基类的构造方法

问题描述 投票:0回答:2

我有两组遵循以下模式的mixin基类

// base class taking one contructor argument
struct OneArgBase
{
  const double x;

  template<typename T>
  OneArgBase(const T & t) :
    x(t.x)
  {}
};

// base class taking two constructor arguments
struct TwoArgBase
{
  const double y;

  template<typename T, typename U>
  TwoArgBase(const T & t, const U & u) :
    y(t.y + u.y)
  {}
 };

从这些基本类中,我得出了两组混合类

template<typename ... Mixins>
struct OneArgMix : Mixins...
{
  template<typename T>
  OneArgsMix(const T & t) :
    Mixins(t)...
  {}
};

template<typename ... Mixins>
struct TwoArgMix : Mixins...
{
  template<typename T, typename U>
  TwoArgsMix(const T & t, const U & u) :
    Mixins(t, u)...
  {}
};

我现在面临的问题是,我想将遵循OneArgBase模式的类传递给TwoArgMix

using Mix = TwoArgMix<TwoArgBase, OneArgBase>;

template<typename ... Mixins>
struct TwoArgMix : Mixins...
{
  template<typename T, typename U>
  TwoArgsMix(const T & t, const U & u) :
    Mixins(t, u)... // if Mixins is TwoArgBase
    Mixins(t)... // if Mixins is OneArgBase
  {}
};

但不知道两个如何以这样的方式编写TwoArgMix的构造函数:仅遵循OneArgMix模式的Mixin基类的第一个模板参数。如果可能的话,我想避免将伪参数写入OneArgMix构造函数,因为OneArgMix也需要这些类。

c++ constructor c++17 variadic-templates template-mixins
2个回答
0
投票

使用工厂,您可能会做类似的事情:

template <typename> struct Tag{};

template<typename T, typename U>
OneArgBase Create(Tag<OneArgBase>, const T& t, const U&)
{
    return OneArgBase(t);
}

template<typename T, typename U>
TwoArgBase Create(Tag<TwoArgBase>, const T& t, const U& u)
{
    return TwoArgBase(t, u);
}

template<typename ... Mixins>
struct TwoArgsMix : Mixins...
{
  template<typename T, typename U>
  TwoArgsMix(const T & t, const U & u) :
    Mixins(Create(Tag<Mixins>{}, t, u))...
  {}
};

Demo


0
投票

您可以尝试使用部分指定的模板。

类似:

template<typename twoarg>
struct TwoArgMix<twoarg, OneArgBase>: ...

将使用OneArgBase作为第二个模板参数的特定实现。

© www.soinside.com 2019 - 2024. All rights reserved.