【发布时间】:2023-03-31 02:56:01
【问题描述】:
我知道这是一种非常令人困惑的提问方式,所以让我解释一下我的意思。我有一个非常简单的界面。
为了争论,我们假设它看起来像:
class Interface
{
public:
virtual ~Interface() = default;
virtual someMethod() = 0;
};
我有一个类是 mixin、decorator 或 CRTP,但我不确定适用什么术语
template< typename interface_t >
class Disablable: public interface_t
{
public:
~Disablable() override = default;
setDisable(const bool shouldDisable) { mDisabled = shouldDisable; }
someMethod() override
{
if(mDisabled) return;
interface_t::someMethod();
}
private:
bool mDisabled = true;
};
我的问题是多态性如何与这个装饰器交互。假设我想从Interface 动态转换为Disablable<Interface>,我的具体实例是Disablable<Interface>吗?
例如,假设我有一个实现
class ConcreteImplementation: public Interface
{
void someMethod() override
{
std::cout << "I printed to cout" << std::endl;
}
};
在代码的其他地方我实例化了一个禁用,因此,
std::unique_ptr<Interface> pInterface(new Disablable<ConcreteImplementation>());
有没有办法将pInterface 解释为Disablable?
基本上,这是真的吗:
dynamic_cast<Disablable<Interface>>(new Disablable<ConcreteImplementation>) != nullptr?
换一种方式问,如果Derived 是一个 Base,是一个Decorated<Derived> 一个Decorated<Base>?
【问题讨论】:
-
我没有看到你从上面的代码中得到任何东西。您的示例中是否缺少某些内容?
-
好吧,
Disposable是一个装饰器。如果是 CRTP,则基类将通过模板参数了解派生类,而不是从模板参数派生的派生类。
标签: c++ polymorphism crtp dynamic-cast