低调最佳实践(C ++) [英] Downcasting best-practice (C++)

查看:61
本文介绍了低调最佳实践(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静态代码分析工具往往会在将基类向下转换为派生类"的过程中徘徊很多,而且我还找到了一些编码标准指南,这些指南没有提到这样做,所以我想知道什么是最佳实践方式.

Static code analysis tools tend to ramble a lot about "downcasting a base class to a derived class" and I also found a couple of coding standard guides, which mention not to do this so I was wondering what is the best-practice way.

这是我的用例:

我有一个Base(接口),DerivedA,DerivedB类,然后是一个包含Base指针的数组.

I have a Base (interface), DerivedA, DerivedB classes and then an array containing Base pointers.

然后,我遍历数组并基于一个标志,确定对象是DerivedA还是DerivedB,将其向下转换并从外部对对象进行一些随机填充.

Then I iterate through the array and based on a flag, I determine if the object is DerivedA or DerivedB, cast it down and do some random stuff to the object from the outside.

基本上是这样的:

// arr is of type Base**
for (int i = 0; i < size; ++i)
{
    // doMagic has an overload for both types
    if (arr[i]->isDerivedA())
    {
        doMagic(reinterpret_cast<DerivedA*>(arr[i]));
    }     
    else if (arr[i]->isDerivedB())
    {
        doMagic(reinterpret_cast<DerivedB*>(arr[i]));
    }
}

关于重新解释,由于嵌入式平台的限制(与C ++ 11相同),我无法使用dynamic_cast,但是作为接口的基类保证对象是DerivedA或DerivedB.

Bout the reinterpret, I cannot use dynamic_cast due to embedded platform restrictions (the same for C++11), but the Base class being an interface guarantees that the object is either DerivedA or DerivedB.

我可以使DerivedA和DerivedB仅实现纯虚拟调用,因此我不必担心向下转换任何东西,但是DerivedA和DerivedB类非常专业,而doMagic会对实例执行完全不同的事情...

I could make DerivedA and DerivedB only implement pure virtual calls, thus i wouldn't have to worry about downcasting anything, but the DerivedA and DerivedB classes are very much specialized and doMagic does completely different things with the instances...

所以我想知道你们是如何实现的-拥有一个非常不同的对象的单个数组,但是继承自一个基础,遍历它们并从外部做一些专门的事情.

So I was wondering how you guys approach this - having a single array of very different objects, but inherited from a single base, iterating through them and doing some specialized stuff from the outside.

推荐答案

您可能应该尝试使用访客模式. 这是一个简单的示例:

You probably should try to use visitor pattern. Here is a simple example:

#include <cstdio>

class A;
class B;
class Visitor {
public:
    void visit(A &a) {
        printf("Visited A\n");
    }

    void visit(B &) {
        printf("Visited B\n");
    }
};


class A {
public:
    virtual ~A() { }

    virtual void applyVisitor(Visitor &v) {
        v.visit(*this);
    }
};

class B : public A {
public:
    ~B() override { }

    void applyVisitor(Visitor &v) override {
        v.visit(*this);
    }
};


int main() {
    A a;
    B b;

    Visitor v;

    a.applyVisitor(v);
    b.applyVisitor(v);


    return 0;
}

这篇关于低调最佳实践(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆