alexeykuzmin0 alexeykuzmin0 - 3 months ago 5
C++ Question

Is there any way for compile-time check of string user-defined literal?

I'm writing a user-defined

string
literal to convert names of months into their numbers. The expected usage of this literal is something like

"Nov"_m


which should return
11
.

At the moment my code looks like

constexpr Duration operator ""_m(const char* str, size_t len)
{
return convert_month_to_int(str, len);
}


where
constexpr int convert_month_to_int(const char, size_t)
is a function which does the actual conversion (or returns
-1
if the month name is incorrect).

The problem is that I would like to show some kind of compile error if the string passed to this literal does not name any month. I tried using
static_assert
in the following way:

constexpr Duration operator ""_m(const char* str, size_t len)
{
static_assert(convert_month_to_int(str, len) > 0, "Error");
return convert_month_to_int(str, len);
}


but this does not work since the compiler is not sure that
convert_month_to_int(str, len)
will be a constant expression.

Is there any way of achieving this behavior?

Answer

I agree with suggestion to use an enum instead.

But anyways, the usual way to signal an error like this in a constexpr function is to throw an exception.

constexpr Duration operator ""_m(const char* str, size_t len)
{
    return convert_month_to_int(str, len) > 0 ? convert_month_to_int(str, len) : throw "Error";
}

See also this question for instance.

Comments