学习OsgEarth源码的时候,看到一种保存参数的方式,自己整理实现一下。
作为笔记:
#include "stdafx.h"
class CBaseValue
{
public:
virtual ~CBaseValue()
{
}
};
template<class T>
class CValue : public CBaseValue
{
public:
CValue(T& t)
{
m_value = t;
}
T Get()
{
return m_value;
}
public:
T m_value;
};
#include <map>
class CValueContianer
{
std::map <std::string, CBaseValue*> m_ValueMap;
public:
template<class T>
bool SetValue(std::string key, T value)
{
CValue<T>* p = new CValue<T>(value);
if (p)
{
CValue<T>*tmp = dynamic_cast<CValue<T>*>(m_ValueMap[key]);
m_ValueMap[key] = p;
if (tmp)
{
delete tmp;
}
return true;
}
else
{
return false;
}
}
template<class T>
bool GetValue(std::string key, T& v)
{
CValue<T>* p = dynamic_cast<CValue<T>* >(m_ValueMap[key]);
if (p)
{
v = p->Get();
return true;
}
else
{
return false;
}
}
};
struct AA
{
int a;
double b;
char* p;
std::string s;
};
#include <vector>
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
CValueContianer d;
d.SetValue("speed", 123);
d.SetValue("speed", 456);
d.SetValue("info.speed", std::string("ad"));
std::string info;
d.GetValue("info",info);
int speed;
d.GetValue("speed", speed);
AA a;
a.a = 1;
a.b = 2.23;
a.p = "abcd";
a.s = "2345556";
d.SetValue("struct", a);
AA b;
d.GetValue("struct", b);
std::vector<int> aa;
for (int i = 0; i < 10; i++)
{
aa.push_back(i);
}
d.SetValue("vector", aa);
std::vector<int> bb;
d.GetValue("vector", bb);
for (int i = 0; i < bb.size(); i++)
{
printf("%d\n", bb[i]);
}
return 0;
}
···