C++运行时选择变量类型

C++ Variable Type Selection at Runtime

本文关键字:类型 变量 选择 运行时 C++      更新时间:2023-10-16

>我正在升级一个为特定硬件接口编写的旧应用程序。 我现在需要向现有应用程序添加对现代硬件的支持。

为此,我想为每个硬件类型创建一个类,并在用户选择其系统中的硬件时将变量分配给一种类型或另一种类型。

例如:

HardwareType1 和类 HardwareType2 都存在具有相同的成员函数。

object HW;  
if (userHwType = 1)  
    // initialize HW as a HardwareType1 class
}  
else{  
    // initialize HW as a HardwareType2 class  
}

现在,我可以在整个代码中使用HW.doSomething(),而无需在每次与硬件交互时对硬件类型设置条件。

敢肯定这是非常基本的,但老实说,我什至不知道这叫什么或搜索什么术语。

谢谢!

创建一个抽象基类,并从中派生两个具体的类:一个实现 type1,另一个实现 type2:

class Hardware
{
public:
    virtual ~Hardware() {};
    virtual void doSomething() = 0;
};
class Hardware1: public Hardware
{
public:
    void doSomething() { // hardware type1 stuff. }
};

class Hardware2: public Hardware
{
public:
    void doSomething() { // hardware type2 stuff. }
};

然后创建必要的实例:

std::unique_ptr<Hardware> hardware(1 == userHwType ? new Hardware1() : 
                                                     new Hardware2());
hardware->doSomething();

如果您的编译器不支持 C++11,则std::unique_ptr将不可用。替代智能指针将boost::scoped_ptr(或boost::shared_ptr)。

将多态性与一个常见的抽象基类一起使用,如下所示:

class HardwareBase
{
public:
    virtual void Open() = 0;
    virtual void Close() = 0;
    virtual ~HardwareBase() {};
};

然后派生具体的硬件类型:

class HardwareType1 : public HardwareBase
{
public:
    virtual void Open() {...}
    virtual void Close() {...}
};

并选择所需的硬件实例:

std::unique_ptr<HardwareBase> hw;  
if (userHwType == 1)  
    hw.reset(new HardwareType1());
else
    hw.reset(new HardwareType2());
// And use it like this:
hw->Open();

请注意,您现在需要一个指向所选对象实例的指针。使用unique_ptr在退出时自动将其删除。

要搜索的术语是多态性;这是通过通用接口与不同类型的交互的一般术语。

在C++中,如果需要在运行时选择行为,通常的方法是定义一个抽象接口,该接口使用虚函数充当具体类型的基类 - 要调用的函数在运行时根据对象的真实类型选择。

// Abstract interface
class Hardware {
public:
    virtual ~Hardware() {}  // needed to safely delete objects
    virtual void doSomething() = 0;  // must be implemented by each concrete type
};
// One concrete type
class HardwareType1 : public Hardware
{
    HardwareType1() { /* initialise */ }
    void doSomething() { /* implementation for this type of hardware */ }
};
// Another concrete type
class HardwareType2 : public Hardware
{
    HardwareType2() { /* initialise */ }
    void doSomething() { /* implementation for this type of hardware */ }
};

现在,您可以选择要创建的内容,然后使用抽象接口进行交互:

// Create the correct type, depending on user input
std::unique_ptr<Hardware> hw
    ((userHwType == 1) ? new HardwareType1 : new HardwareType2);
// Do the right thing depending on the type
hw->doSomething();

您可以搜索工厂方法。这是您尝试实现的模式的名称