非常基本的问题:如何short
用C++ 编写文字?
我知道以下内容:
2
是一个 int
2U
是一个 unsigned int
2L
是一个 long
2LL
是一个 long long
2.0f
是一个 float
2.0
是一个 double
'\2'
是一个char
.但是我怎么写short
文字呢?我尝试了,2S
但它给出了编译器警告.
小智 81
((short)2)
Run Code Online (Sandbox Code Playgroud)
是的,它不是一个简短的文字,更像是一个铸造的int,但行为是一样的,我认为没有直接的方法.
这就是我一直在做的事情,因为我找不到任何关于它的东西.我猜想编译器会很聪明地编译它,好像它是一个短文字(即它实际上不会分配一个int,然后每次都抛出它).
以下说明您应该担心多少:
a = 2L;
b = 2.0;
c = (short)2;
d = '\2';
Run Code Online (Sandbox Code Playgroud)
编译 - >反汇编 - >
movl $2, _a
movl $2, _b
movl $2, _c
movl $2, _d
Run Code Online (Sandbox Code Playgroud)
小智 50
C++ 11为您提供了非常接近您想要的东西.(搜索"用户定义的文字"以了解更多信息.)
#include <cstdint>
inline std::uint16_t operator "" _u(unsigned long long value)
{
return static_cast<std::uint16_t>(value);
}
void func(std::uint32_t value); // 1
void func(std::uint16_t value); // 2
func(0x1234U); // calls 1
func(0x1234_u); // calls 2
// also
inline std::int16_t operator "" _s(unsigned long long value)
{
return static_cast<std::int16_t>(value);
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*urr 28
即便是C99标准的作者也因此而陷入困境.这是Danny Smith的公共领域stdint.h
实现的片段:
/* 7.18.4.1 Macros for minimum-width integer constants
Accoding to Douglas Gwyn <gwyn@arl.mil>:
"This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC
9899:1999 as initially published, the expansion was required
to be an integer constant of precisely matching type, which
is impossible to accomplish for the shorter types on most
platforms, because C99 provides no standard way to designate
an integer constant with width less than that of type int.
TC1 changed this to require just an integer constant
*expression* with *promoted* type."
*/
Run Code Online (Sandbox Code Playgroud)
Ale*_*evo 14
如果您使用Microsoft Visual C++,则每个整数类型都有可用的文字后缀:
auto var1 = 10i8; // char
auto var2 = 10ui8; // unsigned char
auto var3 = 10i16; // short
auto var4 = 10ui16; // unsigned short
auto var5 = 10i32; // int
auto var6 = 10ui32; // unsigned int
auto var7 = 10i64; // long long
auto var8 = 10ui64; // unsigned long long
Run Code Online (Sandbox Code Playgroud)
请注意,这些是非标准扩展,不可移植.事实上,我甚至无法在MSDN上找到这些后缀的任何信息.
jim*_*oon 10
您还可以使用伪构造函数语法.
short(2)
Run Code Online (Sandbox Code Playgroud)
我发现它比铸造更具可读性.
小智 7
一种可能性是为此目的使用 C++11“列表初始化”,例如:
short{42};
Run Code Online (Sandbox Code Playgroud)
此解决方案的优点(与当前接受的答案中的强制转换相比)是它不允许缩小转换范围:
auto number1 = short(100000); // Oops: Stores -31072, you may get a warning
auto number2 = short{100000}; // Compiler error. Value too large for type short
Run Code Online (Sandbox Code Playgroud)
请参阅https://en.cppreference.com/w/cpp/language/list_initialization#Narrowing_conversions以了解禁止使用 list-init 的缩小转换