jha*_*a-G 1 c++ enums user-defined-literals constexpr
可以将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;
}
Run Code Online (Sandbox Code Playgroud)
0x4141在这种情况下,编译器会编译它并在编译时生成一个Hexa-decimal常量.它确实生成一个编译警告:
main.cpp:9:14: warning: multi-character character constant [-Wmultichar]
XX = 'AA', // 0x4141 or 0100 0001 0100 0001
Run Code Online (Sandbox Code Playgroud)
我的问题是,我们可以避免这种警告吗?
或者我们可以编写一个更优雅的代码来实现类似的结果,可能使用模板和constexpr?
我正在寻找一种便携式替代方案,这样我就可以在不影响核心逻辑的情况下将其作为重构的一部分.
我想你想要这样的东西 - 它不使用多字符文字BTW,而是用户定义的文字调用_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;
}
Run Code Online (Sandbox Code Playgroud)
输出(演示):
4141
4242
4343
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
197 次 |
| 最近记录: |