C++一个多参数的保存方式

学习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;
	}
···
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

站长漫谈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值