Dynamic Object in C++?

后端 未结 5 483
野的像风
野的像风 2021-01-24 14:12

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

5条回答
  •  北海茫月
    2021-01-24 14:29

    You can do something very similar with std::map:

    std::map myObject;
    myObject["somethingIJustMadeUp"] = myStr;
    

    Now if you want generic value types, then you can use boost::any as:

    std::map 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;
    

    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(myObject["Xyz"]);
        std::cout <<"Stored value is string = " << value << std::endl;
      }
    }
    

    This also shows how you can use boost::any_cast to get the value stored in object of boost::any type.

提交回复
热议问题