Jump to content

Rick's Blog

  • entries
    65
  • comments
    96
  • views
    24,806

Dynamic properties!


Rick

2,543 views

 Share

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;
}

  • Upvote 4
 Share

3 Comments


Recommended Comments

This would give you the ability to reflect! :D

 

Could come in fantastically handy if you ever wanted to wrap a GUI around your engine to make edits.

Link to comment

@BLaBZ I agree. Other usages I was thinking about was a game engine with your own editor. If you combine this with component design you can get some pretty flexible things made via an editor. You could add any properties to a game object without coding and do it via an editor.

Link to comment
Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...