有兩種現有的類,一類是SrcField
它返回混凝土類型值,而另一個是一個聯合DSTField
,其限定相應的數據類型。如何簡化這個多餘的C++代碼?
class SrcField
{
public:
signed char GetInt8();
unsigned char GetUInt8();
short GetInt16();
unsigned short GetUInt16();
int GetInt32();
unsigned int GetUInt32();
float GetFloat();
double GetDouble();
bool GetBool();
DataType GetType();
private:
DataType m_type;
DSTField m_data;
};
union DSTField
{
signed char m_int8;
unsigned char m_uint8;
short m_int16;
unsigned short m_uint16;
int m_int32;
unsigned int m_uint32;
float m_float;
double m_double;
bool m_bool;
};
當我使用這兩個類,則應用程序是如以下。 這是非常多餘的;有沒有什麼好的方法來簡化它,比如模板,泛型編程等?
int main()
{
SrcField sf;
DSTField df;
switch(sf.GetType())
{
case TYPE_INT8:
df.m_int8 = sf.GetInt8();
break;
case TYPE_UINT8:
df.m_uint8 = sf.GetUInt8();
break;
case TYPE_INT16:
df.m_int16 = sf.GetInt16();
break;
case TYPE_UINT16:
df.m_uint16 = sf.GetUInt16();
break;
case TYPE_INT32:
df.m_int32 = sf.GetInt32();
break;
case TYPE_UINT32:
df.m_uint32 = sf.GetUInt32();
break;
case TYPE_FLOAT:
df.m_float = sf.GetFloat();
break;
case TYPE_DOUBLE:
df.m_double = sf.GetDouble();
break;
case TYPE_BOOL:
df.m_bool = sf.GetBool();
break;
default:
break;
}
}
'boost :: variant'或'std :: variant'如何? –
你爲什麼使用getters? – 2017-05-26 08:08:19
..或'的boost :: any'(雖然我更喜歡'variant'太多,如果設定的種類受到限制。 – Nim