Let a Class store unknown Data

纵然是瞬间 提交于 2019-12-11 09:12:32

问题


Issue about Storeing unknown Data in a Class

How can I provide a class in C++ which is able to store any number of variables each of any type? From inside and outside of the class I would like to read, add, modify and delete these data.

So what I am looking for is maybe a list where the datatypes can vary.

Example how the Usage could look like

Class Object();
Object->Storage->Create("position", "float");    // create
Object->Storage->Write("position", 42.0f);       // write
int Result = Object->Storage->Read("position");  // read
Object->Storage->Delete("position");             // delete

How to do that or why to do it in another Way

My question is if there is a common approach for this problem and what a good solution is. If my thoughts were not correct and there is another technique or place to store data for my aim (next paragraph) please tell me.

Optional Background Information and Context

The reason behind this need is that I am writing a kind of component based game engine. There are Components and Systems. A System could be the title menu or a world level and I can add as many Components to it as I wish. Every game tick, the System calls a specified method over all of its Components. Components are e.g. Physics, Terrain, Draw, Characters, Sound, ... The mentioned unknown data structure is what a Component should be able to store in its System. The Component is nearly static and its state depends on the storage it uses. This Storage system is (together with the event manager) used to communicate between Components.

Edit:

By researches I figured out that what I want is called Data Centered or Data Oriented in software design. Now I have a starting point to do more research on this topic. Thank you Michael Anderson for your answer, probably I will use that.


回答1:


You probably want to use boost::any for this kind of thing.

Your code will look like this:

std::map<std::string,boost::any> object;
object["position"] = 42.0f;

//This will throw if the type is wrong
int Result = boost::any_cast<float>(object["position"]);
object.erase("position");



回答2:


Does the Standard Template Library (STL) - more specifically, the use of a map - not work for your needs?

http://en.cppreference.com/w/cpp/container/map

You can use the map to hold values which are either:

1) a "CustomObject", which is a union of all possible variable / object types.

2) a pointer to the actual objects / variables.



来源:https://stackoverflow.com/questions/12927444/let-a-class-store-unknown-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!