In the following example I would like to be told at compile time that the conversion from long to int changes the value just like I do if I don't use the user defined literal.
#include <cassert>
constexpr int operator "" _asInt(unsigned long long i) {
// How do I ensure that i fits in an int here?
// assert(i < std::numeric_limits<int>::max()); // i is not constexpr
return static_cast<int>(i);
}
int main() {
int a = 1_asInt;
int b = 99999999999999999_asInt; // I'd like a warning or error here
int c = 99999999999999999; // The compiler will warn me here that this isn't safe
}
I can work out a few ways of getting a runtime error but I'm hoping there is some way to make it a compile time error since as far as I can see all of the elements can be known at compile time.
CodePudding user response:
Make it consteval
:
consteval int operator "" _asInt(unsigned long long i) {
if (i > (unsigned long long) std::numeric_limits<int>::max()) {
throw "nnn_asInt: too large";
}
return i;
}
int main() {
int a = 1_asInt;
// int b = 99999999999999999_asInt; // Doesn't compile
int c = 99999999999999999; // Warning
}
In C 17, you can use a literal operator template, but it's a bit more involved:
template<char... C>
inline constexpr char str[sizeof...(C)] = { C... };
// You need to implement this
constexpr unsigned long long parse_ull(const char* s);
template<char... S>
constexpr int operator "" _asInt() {
constexpr unsigned long long i = parse_ull(str<S..., 0>);
static_assert(i <= std::numeric_limits<int>::max(), "nnn_asInt: too large");
return int{i};
}