简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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