How can I range check C++14 user defined literals?

You should short-circuit your test against an exception throw, which is an expression and cannot be constexpr. When you pass in a value which doesn't pass this test, the compiler sees an expression, when you pass in an acceptable value, it sees a constexpr value.

#include <exception>
#include <iostream>
#include <limits>

struct MyShort
{
    short  data;
    constexpr MyShort(const short arg) : data(arg) {}
};

constexpr MyShort operator "" _MyShort(const unsigned long long arg)
{
    return (arg > std::numeric_limits<short>::max()) ? throw std::exception() : static_cast<short>(arg);
}

struct UseMyShort
{
    MyShort constexpr static  var1 = 1000_MyShort;
    short constexpr static    var2 = 100000;
};

int main ( int argc, char** argv )
{
  std::cout << UseMyShort::var1.data;
  std::cout << UseMyShort::var2;
}

References: Andrzej's C++ blog describes this:

  • User-defined literals — Part I
  • Compile-time computations

Tags:

C++