Probably a common one, but can't find any existing topic here.
So I have a class with a private struct with many members. I want to write getters and setters for single members, but it would be long and repetitive to write one getter/setter for each member ... how to be generic easily ?
class C {
public:
typedef struct S {
int a, b, c, d, e, f, g, h;
}S;
void setS(S new_struct);
S getS();
void setSElement(????, int value);
int getSElement(????);
private:
S data;
}
What to replace the ????? with to directly refer to which element of S I want (a through h) ?
No need to say, I need the struct to remain a struct and not be mingled with my other class members, and I also need to be able to get/set the struct entirely at once.
Thanks in advance,
Charles
This is a bad idea if your motivation is but it would be long and repetitive to write one getter/setter for each member ....
It is useful for the user of C
to have explicit names for each member. This is how almost all languages supporting OOP are designed. Maybe smalltalk being the exception.
You also mention you have to do validation for the setters. The setSElement
function would quickly become complex.
If you want to keep type-safety for the function call You get even more code to accomplish that.
That being said, if you want a suggestion for what ???? could be, a simple enum would be fine.
class C{
public:
enum SElement{ a, b ...
setSElement(SElement member, int value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With