簡體   English   中英

與 32 位和 64 位平台的 int64_t 匹配的整數文字?

[英]Integer literal that matches int64_t for 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;
}

int64_tlong的平台上, 0LL是一種不同的類型,重載決議不喜歡它而不是double

int64_t long long時(包括在 Windows x64 上),我們對0L有同樣的問題。

0LL在 32 位和 x86-64 Windows ABI (LLP64) 中都是int64_t ,但其他操作系統使用 x86-64 System V,它是一個 LP64 ABI。當然,可移植到非 x86 系統的東西會很好。)

您可以為int64_t制作自定義用戶定義的文字,例如

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

然后你的函數調用會變成

f(0_i64);

如果您出於此處所述的原因嘗試使用文字-9223372036854775808 ,這將為您提供不正確的值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM