最近在封装类的过程中,实现算法参数的set、get功能时,发现参数类型不一样,包括 int、double ,很难进行统一,后来想到用 void指针作为突破口。
首先定义 一个map类型 用来存储参数。
map
针对double类型的数据,首先创建double类型的数组,用于存储配置文件中的数据,如果直接进行指针类型转换,后期会发现,所有的double数据转换到 void指针后的地址都是一样的,具体原因搞不清楚.
1)从配置文件Calibration.yml 读取参数,保存在map容器 param中。
直接上代码,
std::ifstream inf;
inf.open(config_path, std::ios_base::in);
if (!inf)
return false;
std::string str;
int i = 0;
while (std::getline(inf, str))
{
int s = str.find(“:”);
int ss = str.find(“%”);
if (s == str.npos ||ss!=str.npos)
continue;
std::string key = str.substr(0, s);
//如果是整形或者float型
std::string temp = str.substr(s + 1);
int s1 = temp.find(“.”);
if (s1 == temp.npos)//int
{
int Value = std::atoi(temp.c_str());
void p = (void*)Value;
param.insert(std::make_pair(key, p));
}
else //float
{
dl[i] = std::atof(temp.c_str());
param.insert(std::make_pair(key, &dl[i]));
i++;
}
}
如果不借助double数组 dl存储参数,param容器里面针对double类型的数据,指针地址是一样的。
2)实现get、set功能
利用迭代器遍历容器 param更方便
void* getConfig(std::string key)
{
auto iter = param.begin();
iter = param.find(key);
if (iter != param.end())
{
return (iter->second);
}
}
在实现set功能时,最后通过 第三个 void* 指针变量进行转换。
void setCongig(std::map
{
for (auto iter = input.begin(); iter != input.end(); iter++)
{
auto i = param.find(iter->first);
if (i != param.end())
{
void* temp = iter->second;
i->second = temp;
}
}
}
3)最后根据返回的 void指针,转换到 int、double类型时,也是有区别的
如
//void 转int
void * p= getConfig(“max_width”);
int value=(int)p;
//void* 转double
void * p= getConfig(“max_distance”);
double value=(double)p;



