How to handle class with multiple data members of

2019-08-30 18:27发布

Suppose I have a class which has many data members of different type, and maybe add more in 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: each time I add a another data member, I need to add get/set function. For some reason I cannot change them to public.

one solution is to use getType/setType function together with 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 any better solution? Thanks.

1条回答
来,给爷笑一个
2楼-- · 2019-08-30 18:54

Here's 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;
}
查看更多
登录 后发表回答