简体   繁体   中英

Is it possible to validate the input to a user-defined literal at compile time

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.

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};
}

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