简体   繁体   English

与 32 位和 64 位平台的 int64_t 匹配的整数文字?

[英]Integer literal that matches int64_t for both 32-bit and 64-bit platforms?

Consider a piece of code below.考虑下面的一段代码。 Is there an integer literal that would compile on both 32-bit and 64-bit platforms?是否有可以在 32 位和 64 位平台上编译的整数文字?

#include <iostream>
#include <cstdint>

void f(double)
{
    std::cout << "double\n";
}

void f(int64_t)
{
    std::cout << "int64_t\n";
}

int main()
{
    f(0L);  // works on 64-bit fails on 32-bit system
    f(0LL); // fails on 64-bit but works on 32-bit system

    f(int64_t(0));              // works on both, but is ugly...
    f(static_cast<int64_t>(0)); // ... even uglier

    return 0;
}

On platforms where int64_t is long , 0LL is a different type and overload resolution doesn't prefer it vs. double .int64_tlong的平台上, 0LL是一种不同的类型,重载决议不喜欢它而不是double

When int64_t is long long (including on Windows x64), we have the same problem with 0L .int64_t long long时(包括在 Windows x64 上),我们对0L有同样的问题。

( 0LL is int64_t in both the 32-bit and x86-64 Windows ABIs (LLP64), but other OSes use x86-64 System V which is an LP64 ABI. And of course something portable to non-x86 systems would be nice.) 0LL在 32 位和 x86-64 Windows ABI (LLP64) 中都是int64_t ,但其他操作系统使用 x86-64 System V,它是一个 LP64 ABI。当然,可移植到非 x86 系统的东西会很好。)

You can make a custom user defined literal for int64_t like您可以为int64_t制作自定义用户定义的文字,例如

constexpr int64_t operator "" _i64(unsigned long long value) 
{ 
    return static_cast<std::int64_t>(value);
}

and then your function call would become然后你的函数调用会变成

f(0_i64);

This will give you an incorrect value if you try to use the literal -9223372036854775808 for the reason stated here如果您出于此处所述的原因尝试使用文字-9223372036854775808 ,这将为您提供不正确的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM