如何解决枚举类在C ++中不接受带连字符/破折号的文本
我正在创建enum class
,但是Eclipse中的CDT编译器抛出错误,因为我的常量列表带有连字符。我无法避免使用连字符/破折号,因为它是产品代码的一部分。有解决方法吗?
enum class ProductCode{
JELLY-BEANS,SALE,TWISTED-TWIRLS,5-STARS
}
解决方法
连字符(-
)不能成为C ++语言标识符的一部分。
标识符是由数字,下划线,小写和大写拉丁字母以及大多数Unicode字符组成的任意长序列。它必须以下划线或字母开头。另请参见cppreference/Identifiers。
通常,下划线(_
)字符用于诸如宏和枚举常量之类的标识符中:
enum class ProductCode {
JELLY_BEANS,SALE,TWISTED_TWIRLS,FIVE_STARS // this also can't start with '5'
}
枚举常量不存储文本,因此无论如何它们都不需要像您的产品代码一样完全格式化。要将枚举常量转换为产品代码,可以执行以下操作:
#include <map>
constexpr const char* textOf(ProductCode code) {
switch (code) {
case ProductCode::JELLY_BEANS: return "JELLY-BEANS";
case ProductCode::SALE: return "SALE";
case ProductCode::TWISTED_TWIRLS: return "TWISTED-TWIRLS";
case ProductCode::FIVE_STARS: return "5-STARS";
}
}
ProductCode codeOf(const std::string &str) {
static const std::map<std::string,ProductCode> map{
{textOf(ProductCode::JELLY_BEANS),ProductCode::JELLY_BEANS},{textOf(ProductCode::SALE),ProductCode::SALE},{textOf(ProductCode::TWISTED_TWIRLS),ProductCode::TWISTED_TWIRLS},{textOf(ProductCode::FIVE_STARS),ProductCode::FIVE_STARS}
};
return map.at(str);
}
,
我无法避免使用连字符/破折号,因为它是产品代码的一部分,可以解决此问题。
在C ++中,不能在任何变量或常量名称中使用连字符-
。
没有解决方法,除了可以使用下划线'_'。
,如所述[1,2],不能用枚举来完成,因为这样您的常数需要是有效的C ++标识符,并且连字符或以数字开头将使其无效。 / p>
但是,作为“替代方法”,您可以使用C ++映射代替:
#include <iostream>
#include <map>
std::map < std::string,int >
ProductCode = {
{"JELLY-BEANS",0},{"SALE",1},{"TWISTED-TWIRLS",2},{"5-STARS",3}
};
int main ()
{
std::cout << "ProductCode[\"TWISTED-TWIRLS\"] is " << ProductCode["TWISTED-TWIRLS"];
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。