如何在c ++中处理具有不同类型的多个数据成员的类? [英] How to handle class with multiple data members of different type in c++?

查看:176
本文介绍了如何在c ++中处理具有不同类型的多个数据成员的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类,它有许多不同类型的数据成员,并且可能在将来添加更多。

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;
   ...

}

问题是:each时间我添加另一个数据成员,我需要添加get / set函数。由于某种原因,我不能将它们更改为公开。

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.

一个解决方案是将getType / setType函数与模板一起使用:

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.

推荐答案

这是一个适合我的策略。

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;
}

这篇关于如何在c ++中处理具有不同类型的多个数据成员的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆