Auto return type of a function in c++ -
i have problem im not able solve. have tried find similar question here, didnt find working solution me.
my structure is:
class base { unsigned int id; }; class position: public base { float x,y; position(float a, float b): x(a), y(b) {} } class mass: public base { float mass; mass(float a): mass(a) {} }
i store pointers attributes in map accesed strings. have function, can return attribute list using names. structure , desired functionality should this:
std::map<string, base*> attributes; ???? getatt(string name) { return attributes[name]; } position pos(1,2); mass mass(25.6); attributes.emplace("test_position", &pos); attributes.emplace("test_mass") &mass); cout << "mass of object " <<getatt("test_mass").mass << endl; cout << "x - position of object " << getatt("test_position").x ; prints: mass of object 25.6 x - position of object 1
this function, addition of attributes , memory managment should encapsuled in class, think wont such problem after thing solved. there way that? thinking templates, dont understand them enough make them work :( thinking not storing attributes in 1 array, way easy. suggestions :)
your getatt return base*, this:
base* getatt(const string& name) { ... }
but base class doesn't provide interface derived class, can't
getatt("test_mass").mass
instead have this:
dynamic_cast<mass*>(getatt("test_mass"))->mass; dynamic_cast<position*>(getatt("test_position"))->x;
there alternatives, example can use tagged union, might complex problem.
by way, [] operator of map create element if doesn't exist, need check getatt isn't returning nullptr.
Comments
Post a Comment