How to handle a class with multiple data members of various types in C ++?

Suppose I have a class that has many data members of various types and may add more in the future

Class A { public: int getA(); void setA(int a); ... private: int m_a; int m_b; double m_c; string m_d; CustomerType m_e; char * m_f; ... } 

The problem is this: every time I add another data item, I need to add a get / set function. For some reason, I cannot change them publicly.

one solution is to use the getType / setType function along with the template:

 Class A { public: int getInt(int id){ switch(id) case ID_A: return m_a; case ID_B: return m_b; ... } void setInt(int id,int i){...} double getDouble(){...} void setDouble(int id,double d){...} ... template<T> T get(); template<> //specialize double get<double>(){return getDouble();} ... private: } 

Is there a better solution? Thanks.

0
source share
1 answer

Here is a strategy that works for me.

 #include <string> struct CustomerType {}; class A { public: template <typename T> struct member { typedef T type; type data; }; struct type_A : member<int> {}; struct type_B : member<int> {}; struct type_C : member<double> {}; struct type_D : member<std::string> {}; struct type_E : member<CustomerType> {}; struct type_F : member<char*> {}; template <typename T> typename T::type get() { return ((T&)allData).data; } template <typename T> void set(typename T::type d) { ((T&)allData).data = d; } private: struct AllData : type_A, type_B, type_C, type_D, type_E, type_F {}; AllData allData; }; int main() { A a; a.set<A::type_A>(20); int b = a.get<A::type_A>(); return 0; } 
+1
source

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


All Articles