C ++中的动态对象? [英] Dynamic Object in C++?
问题描述
我意识到,我很可能会得到很多你不应该这样做,因为...答案,他们是最受欢迎的,我可能完全同意你的推理,但我很好奇是否可能(如我所见)。
I realize that I'll most likely get a lot of "you shouldn't do that because..." answers and they are most welcome and I'll probably totally agree with your reasoning, but I'm curious as to whether this is possible (as I envision it).
可以在C ++中定义一个动态/通用对象类型,其中我可以动态创建存储的属性并在键/值类型的系统中检索?示例:
Is it possible to define a type of dynamic/generic object in C++ where I can dynamically create properties that are stored and retrieved in a key/value type of system? Example:
MyType myObject;
std::string myStr("string1");
myObject.somethingIJustMadeUp = myStr;
请注意,显然 somethingIJustMadeUp
MyType
的定义成员,但它将被动态定义。然后,我可以做一些像:
Note that obviously, somethingIJustMadeUp
is not actually a defined member of MyType
but it would be defined dynamically. Then later I could do something like:
if(myObject.somethingIJustMadeUp != NULL);
或
if(myObject["somethingIJustMadeUp"]);
相信我,我意识到这是多么可怕,但我仍然好奇,
Believe me, I realize just how terrible this is, but I'm still curious as to whether it's possible and if it can be done in a way that minimizes it's terrible-ness.
推荐答案
你可以做一些非常相似的事情,你可以做一些非常相似的事情, code> std :: map :
You can do something very similar with std::map
:
std::map<std::string, std::string> myObject;
myObject["somethingIJustMadeUp"] = myStr;
现在如果你想要一般的值类型,那么你可以使用 boost :: any
as:
Now if you want generic value types, then you can use boost::any
as:
std::map<std::string, boost::any> myObject;
myObject["somethingIJustMadeUp"] = myStr;
您也可以检查值是否存在:
And you can also check if a value exists or not:
if(myObject.find ("somethingIJustMadeUp") != myObject.end())
std::cout << "Exists" << std::endl;
如果您使用 boost :: any
,那么您可以知道 actual 通过调用 .type()
as:
If you use boost::any
, then you can know the actual type of value it holds, by calling .type()
as:
if (myObject.find("Xyz") != myObject.end())
{
if(myObject["Xyz"].type() == typeid(std::string))
{
std::string value = boost::any_cast<std::string>(myObject["Xyz"]);
std::cout <<"Stored value is string = " << value << std::endl;
}
}
这也显示了如何使用 boost :: any_cast
,以获取存储在 boost :: any
类型。
This also shows how you can use boost::any_cast
to get the value stored in object of boost::any
type.
这篇关于C ++中的动态对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!