我正在尝试使用 CRTP 和协方差来实现转发:
class Display { // interface
virtual Display& drawCircle(...) = 0;
virtual Display& drawRect(...) = 0;
// etc. lots of these.
};
class ADisplay<R> : public Display {
virtual Display& getWrapped();
virtual R& drawCircle(...) { getWrapped().drawCircle(...); return *this; }
virtual R& drawRect(...) { getWrapped().drawRect(...); return *this; }
// etc?
};
class B : public ADisplay<B> {
Display& wrapped;
virtual Display& getWrapped() { return wrapped; }
B& methodSpecificToB() {...}
};
这将以“构建器”样式使用:
B b;
b.drawCircle(1,2,3)
.drawRect(4,5,6)
.methodSpecificToB();
这也许不足为奇,因为 ADisplay 是 not completely defined 不起作用。在实例化时。
你能想出其他方法吗?
最佳答案
就像一个提示(我现在不想详细说明,在我这边已经晚了),你总是可以这样做(注意而没有抽象的Display
接口(interface)):
template<class R>
class ADisplay<R>
{
public:
R& drawCircle(...)
{
static_cast<R*>(this)->drawCircleImpl(...);
return *static_cast<R*>(this);
}
R& drawRect(...)
{
static_cast<R*>(this)->drawRectImpl(...);
return *static_cast<R*>(this);
}
protected:
R& drawCircleImpl(...)
{
// May be have some static assert here, if you want to have this method
// 'abstract'. Otherwise provide some reasonable base implementation, or
// delegate to a mixin (provided as another template parameter)
}
R& drawRectImpl(...)
{
// Same as above ...
}
};
抽象接口(interface)的目的是什么,客户端无论如何都必须知 Prop 体的实现方法?
关于用于转发协变返回的 C++ 抽象基础模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18678915/