Dynamic properties!
I like the idea of being able to add dynamic properties at run-time. The following code shows how you can set this up. Instead of declaring a hardcoded amount of variables in a class you could just give it 1 Properties class and it can be dynamic!
#include <string>
#include <map>
using namespace std;
class Prop
{
public:
virtual ~Prop()
{
}
};
template<typename T>
class Property : public Prop
{
private:
T data;
public:
virtual ~Property()
{
}
Property(T d)
{
data = d;
}
T GetValue()
{
return data;
}
};
class Properties
{
private:
map<string, Prop*> props;
public:
~Properties()
{
map<string, Prop*>::iterator iter;
for(iter = props.begin(); iter != props.end(); ++iter)
delete (*iter).second;
props.clear();
}
template<typename T>
void Add(string name, T data)
{
props[name] = new Property<T>(data);
}
template<typename T>
T Get(string name)
{
Property<T>* p = (Property<T>*)props[name];
return p->GetValue();
}
};
int main()
{
Properties p;
p.Add<int>("age", 10);
int age = p.Get<int>("age");
return 0;
}
- 
					
						
					
							
								 4 4
 
		 
	 
							
3 Comments
Recommended Comments