検討:
// member data omitted for brevity
// assume that "setAngle" needs to be implemented separately
// in Label and Image, and that Button does need to inherit
// Label, rather than, say, contain one (etc)
struct Widget {
Widget& move(Point newPos) { pos = newPos; return *this; }
};
struct Label : Widget {
Label& setText(string const& newText) { text = newText; return *this; }
Label& setAngle(double newAngle) { angle = newAngle; return *this; }
};
struct Button : Label {
Button& setAngle(double newAngle) {
backgroundImage.setAngle(newAngle);
Label::setAngle(newAngle);
return *this;
}
};
int main() {
Button btn;
// oops: Widget::setText doesn't exist
btn.move(Point(0,0)).setText("Hey");
// oops: calling Label::setAngle rather than Button::setAngle
btn.setText("Boo").setAngle(.5);
}
これらの問題を回避するためのテクニックはありますか?
例: テンプレート マジックを使用して、Button::move が Button& などを返すようにします。
編集setAngle を仮想化することで、2 番目の問題が解決されることが明らかになりました。
しかし、最初の問題は合理的な方法で未解決のままです!
編集:まあ、C++ で適切に行うことは不可能だと思います。とにかく努力してくれてありがとう。