如何在 C++ 中指定 unsigned char 类型的整数文字? [英] How do I specify an integer literal of type unsigned char in C++?

查看:36
本文介绍了如何在 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
}

这篇关于如何在 C++ 中指定 unsigned char 类型的整数文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆