Access struct properties by variable value

I have a margin structure in my class with 4 properties. Instead of writing four different getter / setter methods, I decided that I could do it better:

class myClass { private: struct margin { int bottom; int left; int right; int top; } public: struct getMargin(); void setMargin(string which, int value); }; 

But how can I set the structure property corresponding to the "which" line of setMargin() ? For example, if I call myClass::setMargin("left", 3) , how can I set "margin.left" to "3"? Preferably, preserving the structure of the POD ? I really can't figure it out ...

And on the side of the note, is this really better than writing a lot of getter / setter methods?

Thanks!

+6
source share
5 answers

Firstly, your idea is terrible ... :)

Note that you don't even have a margin member (added below)

I would use enum for this if you don't want setters / receivers for each property:

 class myClass { private: struct margin { int bottom; int left; int right; int top; } m; // <--- note member variable public: enum Side { bottom, left, rigth, top }; struct getMargin(); void setMargin(Side which, int value); }; 

and have a switch inside setMargin .

 void myClass::setMargin(Side which, int value) { switch (which) { case bottom: m.bottom = value; break; //.... } } 
+8
source
 class myClass { private: int margin[4]; public: enum Side { bottom, left, rigth, top }; void setMargin(Side which, int value); }; void myClass::setMargin(Side which, int value) { margin[which]=value; } 
+3
source

Any suggestion by Lucian or Gere would be my advantage. If you really want to find a string reference, however, it is probably best to do this with an associative container.

 class MyClass { std::map<std::string, int> m_; public: bool setMargin(std::string which, int value) { std::map<std::string, int>::iterator i = m_.find(which); if (i == m_.end()) return false; i->second = value; return true; } }; 

This is only useful if you have a dynamic interface that allows your user to define their own fields by name.

+1
source

You can use a "relative pointer" that indicates the distance from the struct address to the point of the special element. For instance:

 SetMargin(FIRST,5); 

Which FIRST has a value of enum and is 0.

 SetMargin(SECOND,100); 

SECOND is 4 since int is 4 bytes in my system

implementation:

 void SetMargin(enum margin_elements,int a) { int *relative=struct_pointer+(int*)margin_elements; *relative_pointer=a; return; } 
0
source

If you can make the brand publicly available, you can get rid of get, set methods:

 class myClass { public: struct Margin { int bottom; int left; int right; int top; }; Margin margin; }; myClass mc; mc.margin.bottom = mc.margin.left; 
0
source

Source: https://habr.com/ru/post/922764/


All Articles