我想我缺少明显的东西,但这是我的问题
带有纯抽象类IFoo
class IFoo
{
public:
virtual bool isBar1() const=0;
virtual bool isBar2() const=0;
};
和2个实现
class Foo1 : public IFoo
{
public:
bool isBar1() const override { return true;}
bool isBar2() const override { return false;}
};
class Foo2 : public IFoo
{
public:
bool isBar1() const override { return false;}
bool isBar2() const override { return true;}
};
我有一个管理类,必须根据变量protocol
调用正确的方法
class FooManager : public IFoo
{
public:
bool isBar1() const override
{
switch(protocol)
{
case 1: return Foo1().isBar1();
case 2: return Foo2().isBar1();
default: return false;
}
}
bool isBar2() const override
{
switch(protocol)
{
case 1: return Foo1().isBar2();
case 2: return Foo2().isBar2();
default: return false;
}
}
void setProtocol(int proto){this->protocol = proto;}
private:
int protocol{0};
};
但是有很多方法,我不想将switch(protocol)
放到任何地方,因为它确实是重复的,并且可以随时添加新的FooX。
我如何在不使用模板的情况下调用正确的替代(假设协议是动态的并且FooManager是持久的)并且无需在每次调用时都使用堆(通过智能指针或类似方法,因为它是针对嵌入式项目的,我们尝试将其尽可能地保留在堆栈上)。
我不能只是创建一个返回IFoo的getFoo()方法,因为它是一个抽象类而且我也无法返回IFoo&,因为它会返回对临时目录的引用。
IFoo& FooManager::getFoo()
{
switch(protocol)
{
case 1: return Foo1();
case 2:
default: return Foo2();
}
//return reference to temporary
}
我还能做什么?
您可以返回std::unique_ptr
,以便获得多态行为,但可以控制返回对象的生存期。
std::unique_ptr<IFoo> FooManager::getFoo()
{
switch(protocol)
{
case 1: return std::make_unique<Foo1>();
case 2:
default: return std::make_unique<Foo2>();
}
}
您可以返回一个unique_ptr,例如
std::unique_ptr<IFoo> FooManager::getFoo() {
switch (protocol) {
case 1: return std::make_unique<Foo1>();
case 2:
default: return std::make_unique<Foo2>();
}
}
这将导致数据成为指针,并且在调用成员函数时应用了多态性