向下铸造和模板解决方案与Python
这是基本的C ++,但我要达到Python实际上看起来更简单的地步。假设:
class Base
{
public:
virtual ~Base() = default;
virtual std::string type() const { return "base"; };
};
class Derived1 : public Base
{
public:
virtual std::string type() const { return "dervied1"; };
};
class Derived2 : public Base
{
public:
virtual std::string type() const { return "dervied2"; };
};
我发现自己具有其他类型的功能:
void process(Base& derived_from_base)
{
};
Q1:我如何知道我要采用的是输入,我应该称其为type()和后来的cast,问题是我认为type()会始终给出“基础”?
Q2: This is so annoying.后来,我必须将输入放在正确的派生类中。我只是想知道Python是否在后台这样做,我确定所有这些都比Python快吗?
Q3:是真的,我可以使用模板替换虚拟函数/继承和所有铸造吗? (听到某个地方,不确定)。
非常感谢。
this is basic C++ but I am getting to a point where python actually seems way simpler. Suppose:
class Base
{
public:
virtual ~Base() = default;
virtual std::string type() const { return "base"; };
};
class Derived1 : public Base
{
public:
virtual std::string type() const { return "dervied1"; };
};
class Derived2 : public Base
{
public:
virtual std::string type() const { return "dervied2"; };
};
I find my self having other functions of type:
void process(Base& derived_from_base)
{
};
Q1: How do I know what I am taking as input, should I call type() and later down cast, problem is I think type() will give always "base"?
Q2: This is so annoying. I later have to down case the input to the correct derived class. I am just wondering if python is doing this in the background, am I sure that with all of this I am faster than python?
Q3: Is it true I can replace virtual function/inheritance and all casting using templates? (heard this somewhere and not sure).
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
A1:保留完整的类型,而不是将其删除到基类。例如而不是
使用
A2:Python有类似的东西:
使用A1的方法,您的速度比任何事物都要快(假设程序中的其他所有内容都不糟糕),因为静态调度:多亏了模板,超负荷分辨率在编译时间发生,因此无需花费任何费用。
A3:使用适当的设计,您可以在大多数情况下做到这一点,例如,请参阅A1。但是,有些事情强迫动态链接:OS API,游戏插件等。在这种情况下,考虑将笨拙的边界部分定位,因此大多数代码都可以像往常一样编写。
注意:没有虚拟函数的继承是完全良好的,并且零值(本身),例如,请参见 crtp 。
A1: Keep the full type instead of erasing it to the base class. E.g. instead of
use
A2: Python has something like this:
With the approach from A1, you are faster than anything (assuming everything else in the program isn't worse) because of static dispatch: thanks to templates, overload resolution happens at compile time and therefore costs nothing.
A3: With proper design, you can do that most of the times, e.g. see A1. However, some things force linking dynamically: OS API, game plugins etc. In such cases, consider localizing the clumsy borderline part, so most of the code can be written as usual.
Note: inheritance without virtual functions is perfectly fine and zero-cost (on its own), e.g. see CRTP.