gpt4 book ai didi

c++ - 如何简化这个冗余的 C++ 代码?

转载 作者:IT老高 更新时间:2023-10-28 23:01:09 25 4
gpt4 key购买 nike

现有的类有两个,一个是SrcField它返回具体类型值,另一个是 union DSTField ,它定义了相应的数据类型。

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

最佳答案

使用 std::variant 您的代码将如下所示:

#include <iostream>
#include <variant>

typedef std::variant<
signed char,
unsigned char,
short,
unsigned short,
int,
unsigned int,
float,
double,
bool
> SrcField, DSTField;

int main()
{
SrcField sf(97.0f);
DSTField df;

df = sf;

if(auto pval = std::get_if<float>(&df))
std::cout << "variant value: " << *pval << '\n';
else
std::cout << "failed to get value!" << '\n';
}

注意:由于是 c++17,对于以前的版本,我建议使用 boost::variantboost::anyAny 类(例如我在我的项目中使用一个基于 this 的类)

关于c++ - 如何简化这个冗余的 C++ 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44196608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com