C++动态属性
C++ dynamic properties
我不知道动态属性是否真的是正确的术语,但我希望能够在运行时通过一些容器定义属性。我要寻找的用法如下:
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::any
或boost::variant
与std::map
结合使用可以满足您的需要。
相关文章:
- 如何在一个属性中动态存储基元类型
- 我可以从样式表 (qss) 更改自定义动态属性吗?
- 动态分配的属性和继承
- 如何根据道具名称动态设置对象的属性?
- 从高度动态的C 数据模型中更新QML:计时器与属性绑定
- C QT5动态属性
- 通过"a pointer of the base class"访问未在基类中声明的子类的方法或属性(动态)
- 从 QObject 中删除动态属性
- 私有属性C++上的动态二维数组
- C++ 类两个动态属性
- Qt:我什么时候可以从qtcreator访问动态属性
- 为@dynamic属性动态创建getter和setter,导致无限循环
- 基于标签高度动态设置窗体的VertScrollBar属性-c++生成器
- C++动态属性
- C++按属性排序的对象动态数组
- C++:如何在类中获取具有动态变量的私有属性
- 无法更改从C++动态创建的 QML 组件的属性
- 在c++中处理类的动态属性
- 如何在C++中动态添加/删除QML属性
- 如何使用qt属性动态显示/隐藏个人定义属性的子属性