与32位和64位平台的INT64_T匹配的整数字面形式?

发布于 2025-02-03 09:10:54 字数 863 浏览 2 评论 0原文

考虑下面的一件代码。是否有一个整数字面形式可以在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;
}

在平台上int64_tlong0ll是另一种类型,而Orderload分辨率不希望它与double

int64_t长长(包括在Windows X64上)时,我们与0L有同样的问题。

0llint64_t在32位和X86-64 Windows ABIS(LLP64)中均使用X86-64 System V Windows ABI(LLP64),这是LP64 ABI。当然,非X86系统可移植的东西会很好。)

Consider a piece of code below. Is there an integer literal that would compile on both 32-bit and 64-bit platforms?

#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.

When int64_t is long long (including on Windows x64), we have the same problem with 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.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

韬韬不绝 2025-02-10 09:10:54

您可以进行自定义用户定义的文字 for int64_t喜欢

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

然后您的函数调用将变成

f(0_i64);

这种情况,如果您尝试使用文字-92233720368547775808,则会为您带来错误的价值。 /45469214/Why-do-the-the-the-the-the-the-int-in-in-rorr-abour-about-abour-amboud-ambiul-function-ove/45469321#45469321“>在这里

You can make a custom user defined literal for int64_t like

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文