避免在使用者函数采用基类时进行强制转换

Avoid Casting when Consumer Function takes a Base Class

提问人:Vero 提问时间:12/1/2022 更新时间:12/1/2022 访问量:25

问:

请如何执行下面的注释行,即“//如何在不投射的情况下做到这一点?我的意思是如何通过改变我的设计来做到这一点,我知道我不能这样做。我想到的一些丑陋的方式:

  1. 选角(对某些人来说可能并不丑陋)快吗?是编译时还是运行时操作,我也可以在没有很多 if 的情况下做到这一点,即请记住评论:“//我不能成为模板,有很多我”。std::static_pointer_cast
  2. 用抛出实现所需的所有成员函数,这很丑陋,而且它确实增加了分配给 .BaseConsumableBaseConsumable
  3. 使用和拥有属性的映射,并使用它知道要查找的内容来处理映射。boost::anyBaseConsumableIOnlyCareAboutCommunOp
#include <iostream>

class BaseConsumable //I can't be a template and there are a lot of me
{
public:
    virtual ~BaseConsumable() = default;
};

class Consumable : public BaseConsumable
{
public:
    virtual ~Consumable() = default;
    virtual void IamSomethingCommunBetweenChilds() const = 0;

protected:
    Consumable() = default;
};

class ConsumableTypeOne : public Consumable
{
public:
    ConsumableTypeOne() : Consumable() {};
    virtual void IamSomethingCommunBetweenChilds() const override
    {
        std::cout << "Im implemented" << std::endl;
    }

    virtual void ImSomthingSpecialOne() const
    {
        std::cout << "I am special One" << std::endl;
    }
};

class ConsumableTypeTwo : public Consumable
{
public:
    ConsumableTypeTwo() : Consumable() {};
    virtual void IamSomethingCommunBetweenChilds() const override
    {
        std::cout << "Im implemented" << std::endl;
    }

    virtual void ImSomthingSpecialTwo() const
    {
        std::cout << "I am special Two" << std::endl;
    }
};


class IOnlyConsumeBaseConsumable
{
public:
    void IOnlyCareAboutCommunOp(const std::shared_ptr<const BaseConsumable>& ImConsumableAndTheyAreLotsOfMe) const
    {
        //ImConsumableAndTheyAreLotsOfMe->IamSomethingCommunBetweenChilds(); //How to do this without casting?
    };
};

如果您遇到这种情况,您能帮助我吗,或者这正是铸造首先存在的原因?(我确实在乎速度)。

C++ 继承 强制转换 基类

评论

0赞 PaulMcKenzie 12/1/2022
建议 -- 如果您使用较短的名称和两个派生类,则可以大大减少这一点。
0赞 Vero 12/1/2022
我刚刚复制粘贴了我的案例,所以我不会错过任何东西,如果它太长,对不起
0赞 Richard Critten 12/1/2022
测试结果,除非您 100% 确定,否则只需使用 .dynamic_cast< Consumable *>(ImConsumableAndTheyAreLotsOfMe.get())static_cast
1赞 Richard Critten 12/1/2022
“..我确实在乎速度......”尽可能编写最容易理解的正确代码。测量以查看它是否符合实际负载下的性能要求。如果需要,请使用探查器查找实际的最差路径。
1赞 Dmitry Kuzminov 12/1/2022
你不是在问访客模式吗?

答: 暂无答案