C++ 动态属性

标签 c++

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

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

关于C++ 动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20225392/

相关文章:

c++ - 如何从另一个文件加载类 - Visual Studio C++

c++ - thread 不是 std c++ 的成员

c++ - 平面的参数化生成

c++ - 传递对对象 C++ 的引用

c++ - 枚举的使用 - 全局和局部

c++ - 使 std::cout 在同一行中一个接一个地输出多个字符串

c++ - 泛化共享指针和 QSharedPointer::data() vs shared_ptr::get()?

c++ - 从非 const 到 const 模板参数的隐式转换在 boost::optional 中不起作用

c++ - 在 C++ 中免费分析?

c++ - 通过迭代器更改集合中的元素