C ++中的通用配置文件解析器设置器

时间:2017-05-30 20:13:03

标签: c++ enums configuration-files unions

我正在研究通用配置文件解析器。

首先,它应该调用一个函数来设置变量的数据类型。

enum type {a,b,c}; 
union{int a; double b; float c;};
void SetTypes(type x, string *names){ 
// names[] contains the names of the variables
// type is what data type from the union needs to be used
union name.x;   //------(1)
}

但是我遇到了字符串[]长度的问题。

所以,我正在以下列方式完成我的功能

void setTypes(type a, string name...){}

有没有办法让它更有效率;以便我可以将相同类型的数据捆绑在一起?

这个程序的目的是让我们不必在代码中预定义数据类型,使配置解析器更加灵活。

这里的第二个问题在标记为(1) 如何制作<union> <varname>.<enum> 发生?其中varname和enum是变量

编辑1:添加了示例

例如,

struct EXAMPLE{
/*Some Code*/
 enum allowed_types {vec3D, complex_num};
union {
Vector3D vec3D;
Complex complex_num;
};
/* More Code*/
};

当我以这种方式调用该函数时

setType(vec3D, {"point1", "point 2", "point3"}, complex_num, {"num1", "num2"});

然后我需要函数来创建变量(每个struct) point1 of type Vector3D point2 of type Vector3D point3 of type Vector3D num1 of type Complex num2 of type Complex

我正在使用枚举,以便我可以更好地控制我使用的类型。 我正在使用union,以便我可以使用指针将值存储在hashmap中,以最大限度地减少空间损失。

1 个答案:

答案 0 :(得分:0)

您可以使用unordered_map<string, int> data_type;来存储每个“名称”的类型。 然后,当您想要返回该值时,可以切换数据类型并正确使用。

switch(data_type[s]){
   case vec3d:
       coordinates.push_back(data[s].vec3d);
       break;
   case complex_num:
       r = get_real(data[s].complex);
       break;
}