我有两组遵循以下模式的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也需要这些类。
最佳答案
编程中的所有问题都可以通过添加另一层间接解决。
如果第二个参数不可构造,我们需要有条件地忽略它。一种方法是将每个mixin包装为另一种有条件地忽略其第二个参数的类型:
template <typename M>
struct WrappedMixin : M
{
template <typename T, typename U>
WrappedMixin(T const& t, U const& u)
: WrappedMixin(t, u, std::is_constructible<M, T const&, U const&>{})
{ }
private:
template <typename T, typename U>
WrappedMixin(T const& t, U const& u, std::true_type /* yes, use both */)
: M(t, u)
{ }
template <typename T, typename U>
WrappedMixin(T const& t, U const&, std::false_type /* no, just one */)
: M(t)
{ }
};
现在,我们的主要构造函数很简单:我们只是从包装的构造函数继承:
template<typename ... Mixins>
struct TwoArgMix : WrappedMixin<Mixins>...
{
template<typename T, typename U>
TwoArgsMix(const T & t, const U & u)
: WrappedMixin<Mixins>(t, u)...
{ }
};
关于c++ - 根据参数数量调用mixin基类的构造方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59838410/