Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : generic getter/setter for each single member of private struct

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

like image 291
C. THIN Avatar asked Sep 07 '25 04:09

C. THIN


1 Answers

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 Cto 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);
like image 161
Captain Giraffe Avatar answered Sep 10 '25 02:09

Captain Giraffe