gpt4 book ai didi

c++ - 如何扩展词法转换以支持枚举类型?

转载 作者:IT老高 更新时间:2023-10-28 21:38:08 24 4
gpt4 key购买 nike

我有以下函数可以将字符串转换为数字数据类型:

template <typename T>
bool ConvertString(const std::string& theString, T& theResult)
{
std::istringstream iss(theString);
return !(iss >> theResult).fail();
}

但是,这不适用于枚举类型,所以我做了这样的事情:

template <typename T>
bool ConvertStringToEnum(const std::string& theString, T& theResult)
{
std::istringstream iss(theString);
unsigned int temp;
const bool isValid = !(iss >> temp).fail();
theResult = static_cast<T>(temp);
return isValid;
}

(我假设 theString 对枚举类型具有有效值;我主要将其用于简单的序列化)

有没有办法创建一个结合了这两者的单一功能?

我对模板参数进行了一些尝试,但没有提出任何建议;不必为枚举类型调用一个函数而为其他所有类型调用另一个函数真是太好了。

谢谢

最佳答案

您必须执行两个步骤。找到一个足够大的整数类型来存储值。您可以使用 unsigned long,但值可能为负数。然后你可以使用 long 但值可以扩展到 unsigned long 的范围。所以没有真正的万能类型。

不过有一个技巧,就是使用重载决议。在这里

template<typename T>
struct id { typedef T type; };

id<char[1]>::type &find_etype(int);
id<char[2]>::type &find_etype(unsigned int);
id<char[3]>::type &find_etype(long);
id<char[4]>::type &find_etype(unsigned long);

如果您的实现支持它,您可以适本地更改它以覆盖 long longunsigned long long。现在,传递一个枚举类型将更喜欢其中一个而不是其他所有类型 - 这是一种可以存储它的所有值的类型。您只需要将返回类型的 sizeof 传递给某个模板。

template<int> struct get_etype;
template<> struct get_etype<1> { typedef int type; };
template<> struct get_etype<2> { typedef unsigned int type; };
template<> struct get_etype<3> { typedef long type; };
template<> struct get_etype<4> { typedef unsigned long type; };

现在,您可以获得正确的类型。您现在需要的只是查看某个类型是否是枚举。如何做到这一点在“C++ 模板 - 完整指南”一书中进行了描述,不幸的是有很多代码。所以我会使用boost的is_enum .放在一起,它可能看起来像

template <typename T>
typename boost::disable_if< boost::is_enum<T>, bool>::type
ConvertString(const std::string& theString, T& theResult)
{
std::istringstream iss(theString);
return !(iss >> theResult).fail();
}

template <typename T>
typename boost::enable_if< boost::is_enum<T>, bool>::type
ConvertString(const std::string& theString, T& theResult)
{
typedef typename get_etype<sizeof find_etype(theResult)>::type
safe_type;

std::istringstream iss(theString);
safe_type temp;
const bool isValid = !(iss >> temp).fail();
theResult = static_cast<T>(temp);
return isValid;
}

希望这会有所帮助。

关于c++ - 如何扩展词法转换以支持枚举类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1528374/

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