简体   繁体   中英

how can i change value type of a object in c++

I have an issue in assigning value to a object. my object definition says:

class myobject {
   public:
   var_type type;
   union value_type value;
   myobject(int value);
   myobject(string value);
   ...
 };

 enum var_type {
    var_int,
    var_str,
    var_float
 };

 union value_type {
    int;
    real;
    string;
 };

 myobject* object = get_object("name");
 //here i need to change its value, i dont have any setvalue function.

Now in some other file i need to update the value of myobject, but i dont know the value type. say initial value_type is int, and my function assigns it a string, i get absurd value at doign GetValue(). what should be more efficient way to get the value type of the object, change my string value to the old value type it supporting and modified it. I cant change in the definition class of myobject.

Thanks Ruchi

With limited information provided in your question I assume that you want to change the value of your pointer "object" depending on input which could string or int or something else.

Check this program, I make use of "boost::any" and typeid. Review this option and test it in your program. Else do explicitly explain with some code example what you want to achieve.

Also union with string would give you compile problems? Is it not?

#include <iostream>
#include <string>
#include <typeinfo>
#include <boost/any.hpp>
#include <boost/unordered_map.hpp>
#include<list>

using namespace std;

class myobject {
  public:
    myobject(int value)
    {cout<<"int ctr"<<endl;}
    myobject(std::string value)
    {cout<<"string ctr"<<endl;}
};

int main()
{
  list<boost::any> valueType;

  std::string valStr("name");

  valueType.push_back(valStr);

  int num = 10;

  valueType.push_back(num);

  myobject* object = NULL;

  for(list<boost::any>::iterator itr = valueType.begin();
      itr != valueType.end();
      ++itr)
  {
    if((*itr).type() == typeid(std::string))
      object = new myobject((boost::any_cast<std::string>(*itr)));
    else if((*itr).type() == typeid(int))
      object = new myobject((boost::any_cast<int>(*itr)));
  }

  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM