Reputation: 9002
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.)
Upvotes: 7
Views: 597
Reputation: 180415
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
Upvotes: 8