如何在 C++ 中指定 unsigned char 类型的整数文字?
我可以指定一个 unsigned long 类型的整数文字,如下所示:
I can specify an integer literal of type unsigned long as follows:
const unsigned long example = 9UL;
对于 unsigned char 我该如何处理?
How do I do likewise for an unsigned char?
const unsigned char example = 9U?;
这是避免编译器警告所必需的:
This is needed to avoid compiler warning:
unsigned char example2 = 0;
...
min(9U?, example2);
我希望避免我目前拥有的冗长解决方法,并且没有在调用 min 的行中出现unsigned char"而不在单独的行上的变量中声明 9:
I'm hoping to avoid the verbose workaround I currently have and not have 'unsigned char' appear in the line calling min without declaring 9 in a variable on a separate line:
min(static_cast<unsigned char>(9), example2);
推荐答案
C++11 引入了用户定义的文字.可以这样使用:
C++11 introduced user defined literals. It can be used like this:
inline constexpr unsigned char operator "" _uchar( unsigned long long arg ) noexcept
{
return static_cast< unsigned char >( arg );
}
unsigned char answer()
{
return 42;
}
int main()
{
std::cout << std::min( 42, answer() ); // Compile time error!
std::cout << std::min( 42_uchar, answer() ); // OK
}
相关文章