提问人:Vero 提问时间:12/1/2022 更新时间:12/1/2022 访问量:25
避免在使用者函数采用基类时进行强制转换
Avoid Casting when Consumer Function takes a Base Class
问:
请如何执行下面的注释行,即“//如何在不投射的情况下做到这一点?我的意思是如何通过改变我的设计来做到这一点,我知道我不能这样做。我想到的一些丑陋的方式:
- 选角(对某些人来说可能并不丑陋)快吗?是编译时还是运行时操作,我也可以在没有很多 if 的情况下做到这一点,即请记住评论:“//我不能成为模板,有很多我”。
std::static_pointer_cast
- 用抛出实现所需的所有成员函数,这很丑陋,而且它确实增加了分配给 .
BaseConsumable
BaseConsumable
- 使用和拥有属性的映射,并使用它知道要查找的内容来处理映射。
boost::any
BaseConsumable
IOnlyCareAboutCommunOp
#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?
};
};
如果您遇到这种情况,您能帮助我吗,或者这正是铸造首先存在的原因?(我确实在乎速度)。
答: 暂无答案
上一个:使用现有父类的值实例化子类
评论
dynamic_cast< Consumable *>(ImConsumableAndTheyAreLotsOfMe.get())
static_cast