C++动态属性

C++ dynamic properties

本文关键字:属性 动态 C++      更新时间:2023-10-16

我不知道动态属性是否真的是正确的术语,但我希望能够在运行时通过一些容器定义属性。我要寻找的用法如下:

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

我似乎无法解决这个问题,因为每个设置的容器都需要在一个模板化的类中,但我不希望每个基元类型都有类,比如int、float等。我在C++中可以使用上述方法吗?

我现在记得了。诀窍是使用一个未模板化的基类,然后创建一个模板化的子类,并使用容器中的基类来存储它,并使用模板化的函数来处理它

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

我认为boost::anyboost::variantstd::map结合使用可以满足您的需要。