这是一个不断演变的代码的真实故事。我们从基于此结构的许多类开始:
class Base
{
public:
virtual void doSomething() {}
};
class Derived : public Base
{
public:
void doSomething() override
{
Base::doSomething(); // Do the basics
// Do other derived things
}
};
Run Code Online (Sandbox Code Playgroud)
有一次,我们需要一个介于 Base 和 Derived 之间的类:
class Base;
class Between : public Base;
class Derived : public Between;
Run Code Online (Sandbox Code Playgroud)
为了保持结构,Between::doSomething()
首先调用Base。但是现在Derived::doSomething()
必须更改为调用Between::doSomething()
...
这适用于 Derived 的所有方法,需要搜索和替换许多调用。
最好的解决方案是使用一些 this->std::direct_parent 机制来避免所有替换并允许轻松管理类拓扑。
当然,只有当有一个直接父级时,才应该编译。
有什么办法可以做到这一点吗?如果不是,这可能是 C++ 委员会的功能请求吗?
我可以建议的是parent
typedef Derived
:
class Base
{
public:
virtual void doSomething() {}
};
class Derived : public Base
{
private:
typedef Base parent;
public:
void doSomething() override
{
parent::doSomething(); // Do the basics
// Do other derived things
}
};
Run Code Online (Sandbox Code Playgroud)
然后引入之后Between
唯一需要的更改Derived
是 typedef 的更改parent
:
class Derived : public Between
{
private:
typedef Between parent;
public:
void doSomething() override
{
parent::doSomething(); // Do the basics
// Do other derived things
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
215 次 |
最近记录: |