gpt4 book ai didi

c++ - 方法链 + 继承不能很好地结合在一起?

转载 作者:IT老高 更新时间:2023-10-28 22:32:18 27 4
gpt4 key购买 nike

考虑:

// 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& 什么的。

edit很明显,第二个问题是通过将 setAngle 设为虚拟来解决的。

但第一个问题仍未以合理的方式解决!

edit:嗯,我想在 C++ 中不可能做到正确。无论如何感谢您的努力。

最佳答案

您可以扩展 CRTP来处理这个。 monjardin 的解决方案朝着正确的方向发展。您现在只需要一个默认的 Label 实现来将其用作叶类。

#include <iostream>

template <typename Q, typename T>
struct Default {
typedef Q type;
};

template <typename T>
struct Default<void, T> {
typedef T type;
};

template <typename T>
void show(char const* action) {
std::cout << typeid(T).name() << ": " << action << std::endl;
}

template <typename T>
struct Widget {
typedef typename Default<T, Widget<void> >::type type;
type& move() {
show<type>("move");
return static_cast<type&>(*this);
}
};

template <typename T = void>
struct Label : Widget<Label<T> > {
typedef typename Default<T, Widget<Label<T> > >::type type;
type& set_text() {
show<type>("set_text");
return static_cast<type&>(*this);
}
};

template <typename T = void>
struct Button : Label<Button<T> > {
typedef typename Default<T, Label<Button<T> > >::type type;
type& push() {
show<type>("push");
return static_cast<type&>(*this);
}
};

int main() {
Label<> lbl;
Button<> btt;

lbl.move().set_text();
btt.move().set_text().push();
}

也就是说,考虑一下这样的努力是否值得增加少量的语法奖励。考虑替代解决方案。

关于c++ - 方法链 + 继承不能很好地结合在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/551263/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com