我有一个类层次结构,我想使用多态性来调用正确的成员函数。在基本层面上这是可行的,但是在尝试使用 Mixin 类来扩展或更改某些类的功能时遇到了问题。基本上,我想在构造从 mixin 继承的对象时对成员值进行一些验证。(我来自 python 背景,很容易创建改变构造函数行为的混合。方法解析顺序保证从构造函数调用的函数首先从派生类调用)在 C++ 中,动态绑定在构造函数中被禁用(我明白原因)。对virtual void init()函数的调用将不起作用,因为总是会调用基类函数。
有什么方法可以保证validate()函数被执行而不需要再次显式定义构造函数?
工厂是一种方法,但我也希望构造函数具有不同的类型参数。
下面显示了一个最小的示例。
非常感谢
class Base
{
Base(){};
//... some virtual functions...
}
class Derived: public Base
{
using Base::Base;
// new constructors
Derived(some pars){};
Derived(other pars){};
//... some virtual functions...
}
template <class B>
class Mixin: public B
{
using B::B;
Mixin()
{
// mixin related constructor code
// maybe some member validation or discretization of a continuous value
// hides B::B(), but is only called if the default constructor is called, not for B::B(pars)
this->validate();
}
void validate(){};
}
class UsingMixin: public Mixin<Derived>
{
using Mixin::Mixin; // inherit all constructors
// I want to avoid defining the same constructors from Derived again,
// since there would be no change
// some functions
}
编辑:实现这一点的一种方法是在 mixin 上使用模板构造函数,但我不知道这种方法的安全性和可用性,因为我需要知道基类中构造函数参数的最大数量。
template <class B>
class Mixin: public B
{
template <class Arg0>
Mixin(Arg0 arg0)
: B(arg0)
{
this->validate();
}
template <class Arg0, class Arg1>
Mixin(Arg0 arg0, Arg1 arg1)
: B(arg0, arg1)
{
this->validate();
}
template <class Arg0, class Arg1, class Arg2>
Mixin(Arg0 arg0, Arg1 arg1, Arg2 arg2)
: B(arg0, arg1, arg2)
{
this->validate();
}
template <class Arg0, class Arg1, class Arg2, class Arg3>
Mixin(Arg0 arg0, Arg1 arg1, Arg2 arg2, Arg3 arg3)
: B(arg0, arg1, arg2, arg3)
{
this->validate();
}
void validate(){}
}