将 void* 强制转换为特定类型的指针的方法签名

Method signature to cast void* to a pointer of specific type

本文关键字:类型 指针 方法 void 转换      更新时间:2023-10-16

请考虑以下场景:

enum Types { NONE, TYPE_A, TYPE_B, TYPE_C }
struct TypeA { int i; double d; };
struct TypeB { int i; float f; };
struct TypeC { double d; };

上述所有struct都彼此无关。

然后有几种方法(不同的签名(可以将上述任何structvector填充为void*,例如:

void GetTypeInstances (std:vector<void*>& typeInstances)
{
    void* inst;
    // some logic to create/fetch `struct` instances as void*
    typeInstances.push_back(inst);
}
void GetTypeInstancesAgain (std:vector<void*>& typeInstances, bool flag)
{
    void* inst;
    // some logic to create/fetch `struct` instances as void* using 'flag'
    typeInstances.push_back(inst);
}

main(),我希望执行以下操作:

int main()
{
    std:vector<void*> typeInstances;
    GetTypeInstances(typeInstances); // fill the vector
    // depending upon the enum type I want to cast the members of the vector
    for (auto i = 0; i < typeInstances.size(); ++i)
    {
        switch(GetType()) // Types GetType(); is the signature
        {
        case TYPE_A:
            auto* inst = static_cast<TypeA*>(typeInstances[i]);
            // access 'inst' members
            break;
        case TYPE_B:
            auto* inst = static_cast<TypeB*>(typeInstances[i]);
            // access 'inst' members
            break;
        case TYPE_C:
            auto* inst = static_cast<TypeC*>(typeInstances[i]);
            // access 'inst' members
            break;
        }
    }
    // ------------------------------------------------------------
    // Using another method to fetch the vector and access the instances
    std:vector<void*> typeInstancesAgain;
    GetTypeInstancesAgain (typeInstancesAgain, false); // fill the vector
    // depending upon the enum type I want to cast the members of the vector
    for (auto i = 0; i < typeInstancesAgain.size(); ++i)
    {
        switch(GetType()) // Types GetType(); is the signature
        {
        case TYPE_A:
            auto* inst = static_cast<TypeA*>(typeInstancesAgain[i]);
            // access 'inst' members
            break;
        case TYPE_B:
            auto* inst = static_cast<TypeB*>(typeInstancesAgain[i]);
            // access 'inst' members
            break;
        case TYPE_C:
            auto* inst = static_cast<TypeC*>(typeInstancesAgain[i]);
            // access 'inst' members
            break;
        }
    }
    // -----------------------------------------------------
    // Repeating the above for several other methods
    return 0;
}

问题 1(有没有办法将switch提取到将void*转换为各自类型的方法?我想删除代码重复。请注意,enum包含更多类型,并且这些类型还有更多相应的struct

我正在考虑一种方法,但由于struct之间没有关系,我不确定如何解决这个问题:

????  Cast(int enumType, void* ptr)
{
    ????
}

问题 2(如果vector仅填充特定类型的实例,此问题会更简单吗?如果是这样,会是什么?

感谢所有可能的线索。

如果你想"//访问'inst'成员",那么你或多或少被迫编写一些代码来在每种情况下做到这一点。

显而易见的OO方法是拥有一个基类和一个纯虚拟的accesinstmembers((函数,显然命名为更明智的东西。