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

时间:2018-03-08 03:59:57

标签: c++ c++11 void-pointers static-cast

考虑以下情况:

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都彼此无关。

然后有几种方法(不同的签名)填充vector以上任何struct的{​​{1}},例如:

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()

Q1)有没有办法将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; } 提取到将switch转换为各自类型的方法?我想删除代码重复。请注意,void*包含更多类型,并且对于这些类型还有更多对应的enum

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

struct

Q2)如果???? Cast(int enumType, void* ptr) { ???? } 仅填充特定类型的实例,这个问题会更简单吗?如果是这样,会是什么?

所有可能的潜在客户都表示赞赏。

1 个答案:

答案 0 :(得分:0)

如果你想&#34; //访问&#39; inst&#39;成员&#34;那么在每种情况下,你或多或少都会被迫写一些代码来做到这一点。

明显的OO方式是拥有一个基类,以及一个纯虚拟的accessinstmembers()函数,显然命名为更合理的东西。