user441521
user441521

Reputation: 6998

C++ dynamic properties

I don't know if dynamic properties is really the right term, but I want to be able to define properties at run-time via some container. The usage I'd be looking for would be something like the following:

Properties p;

p.Add<int>("age", 10);

int age = p.Get<int>("age");

I can't seem to work this out because the container of each setting would need to be in a templated class but I don't want classes for each primitive type like int, float, etc. Is my usage above possible in C++?

Upvotes: 4

Views: 4153

Answers (2)

user441521
user441521

Reputation: 6998

I remember now. The trick was to use a base class that isn't templated and then make a child class that is templated and use the base class in the container to store it and templated functions to handle it.

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

Upvotes: 3

john
john

Reputation: 87957

I think either boost::any or boost::variant in combination with std::map will do what you want.

Upvotes: 2

Related Questions