将 void* 强制转换为特定类型的指针的方法签名
Method signature to cast void* to a pointer of specific type
请考虑以下场景:
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
都彼此无关。
然后有几种方法(不同的签名(可以将上述任何struct
的vector
填充为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((函数,显然命名为更明智的东西。
相关文章:
- 非类型指针和引用模板参数,以及在编译时如何/为什么解析它们.c++
- 如何访问在 c++ 中在类内声明的结构类型指针变量?
- (C )找到基本类型指针的儿童类型
- 表达式必须具有指向对象的指针类型(指针向量)
- 将子项复制构造到父类型指针中
- C 返回类型指针声明
- 调用虚拟函数而不通过类类型指针创建任何对象
- C++ 如何使用类类型指针制作向量
- 为什么基类型指针不能获取派生类对象的地址值?
- 如何在 C++ 中获取映射类型指针,映射
- 如何检查该类型的类型指针是正确对齐的
- 正在转换为短类型指针
- 指向任意类方法的模板非类型指针
- 如何通过强制转换类型指针将字符数组转换为uint16_t
- 指向shared_ptr的不透明类型 C 指针
- C++:从值类型指针强制转换为包含迭代器
- C/C++:访问给定类型指针的位置与访问另一类型指针的相同位置不同
- 比较类型指针
- 数据类型指针使用*(Datatype *)
- 如何打印c++中char类型指针的所有值