gpt4 book ai didi

c++ - 将多字节 ASCII 文字分配给枚举值

转载 作者:行者123 更新时间:2023-11-30 01:42:45 24 4
gpt4 key购买 nike

可以将 ASCII 文字(不能称其为字符串)分配给 enum 值,如下所示:

#include <iostream>
// Macro to handle BIG/LITTLE ENDIAN
// Endianness is suppoesed to handled in this macro
#define TEMP(X) X

enum t
{
XX = 'AA', // 0x4141 or 0100 0001 0100 0001
};

int main()
{
std::cout<<XX<<std::endl;
}

编译器编译它并在编译时生成一个十六进制常量,在本例中为 0x4141。它确实会生成一个编译警告:

main.cpp:9:14: warning: multi-character character constant [-Wmultichar]
XX = 'AA', // 0x4141 or 0100 0001 0100 0001

我的问题是,我们可以避免这个警告吗?

或者我们是否可以编写更优雅的代码来实现类似的结果,可能使用模板和 constexpr?

我正在寻找一种可移植的替代方案,这样我就可以在不影响核心逻辑的情况下将其作为重构的一部分摆脱掉。

最佳答案

我想你想要这样的东西——顺便说一句,它不使用多字 rune 字,而是用户定义的名为 _i64 的文字,定义如下:

#include <iostream>

//implementation of user-defined literal _i64
namespace details
{
constexpr int64_t i64(char const *s, int64_t v)
{
//in C++11, constexpr function body has to be one-line
//though C++14 has relaxed this rule.
return *s ? i64(s+1, v * 256 + *s) : v;
}
}

constexpr int64_t operator "" _i64(char const *s, unsigned long)
{
return details::i64(s, 0);
}

//your use-case.
enum colors
{
red = "AA"_i64, //0x4141
green = "BB"_i64, //0x4242
blue = "CC"_i64 //0x4343
};

int main()
{
std::cout << std::hex << red << std::endl;
std::cout << std::hex << green << std::endl;
std::cout << std::hex << blue << std::endl;
}

输出(demo):

 4141
4242
4343

关于c++ - 将多字节 ASCII 文字分配给枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39144504/

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