施工解决方案期间的虚拟功能 [英] Virtual Function During Construction Workaround
问题描述
我有一个具有虚函数的基类。我想在构造过程中调用该类,因为我希望为每个派生类调用该函数。我知道我在构造过程中不能调用虚拟函数,但是我想不出一种优雅的(即避免重复代码)解决方案。
I've got a base class that has a virtual function. I want to call that class during the construction because I want the function called for each of the derived classes. I know I can't call a virtual function during construction, but I can't think of an elegant (i.e., avoid repeating code) solution.
在构造过程中调用虚拟函数有哪些解决方法?
我想避免这种情况的原因是因为我不想创建仅调用基类的构造函数。
The reason I want to avoid this is because I don't want to have to create constructors that just call the base class.
class A {
public:
A() {
read();
}
// This never needs to be called
virtual void read() = 0;
}
class B:A {
public:
B():A() { };
read() { /*Do something special for B here.*/ }
}
class C:A {
public:
C():A() { };
read() { /*Do something special for C here.*/ }
}
PS:执行此操作的Python方法只是在 A :: read()$中提高
NotImplementedError
c $ c>。我将返回C ++,并且比我想像的还要生锈。
PS: The Python way of doing this is simply to raise NotImplementedError
in A::read()
. I'm returning to C++ and I'm more rusty than I thought.
推荐答案
这是工厂方法,将工厂进入基类:
This is the factory method approach, putting the factory into the base class:
class A {
public:
virtual void read() = 0;
template<class X> static X* create() {X* r = new X;X->read();return X;}
virtual A* clone() const = 0;
};
class B : public A {
B():A() { };
friend class A;
public:
void read() { /*Do something special for B here.*/ }
B* clone() const {return new B(*this);}
};
class C : public A {
C():A() { };
friend class A;
public:
void read() { /*Do something special for C here.*/ }
C* clone() const {return new C(*this);}
};
添加了 clone
方法并具有协变量收益
Added a clone
-method with covariant return type as a bonus.
使用 CRTP :
class A {
public:
// This never needs to be called
virtual void read() = 0;
virtual A* clone() const = 0;
};
template<class D, class B> struct CRTP : B {
D* clone() {return new D(*this);}
static D* create() {return new D();}
};
class B : public CRTP<B, A> {
B() { };
public:
void read() { /*Do something special for B here.*/ }
};
class C : public CRTP<C, A> {
C() { };
public:
void read() { /*Do something special for C here.*/ }
};
这篇关于施工解决方案期间的虚拟功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!