odinthenerd
odinthenerd

Reputation: 5552

how do I assert from constexpr function with exceptions disabled?

If I want to assert a detected error from a C++11 constexpr function in a small processor embedded design turning off interrupts takes away the suggested method of handling errors (see eric nieblers answer here)

Here is a short code example:

constexpr bool isANumber(char c)
{
    return (c >= '0' && c <= '9');
}

constexpr int charToInt(char c)
{
    return (!isANumber(c))? throw std::logic_error("not a number"):
        c - '0';
}

To the best of my knowledge:

What is the work around?

Note: Using C++ in super resource constrained embedded environments one must turn off exceptions because they use excess RAM (my chip has only 16K RAM for example). It is common practice.

Upvotes: 1

Views: 609

Answers (1)

odinthenerd
odinthenerd

Reputation: 5552

I found a workaround for the special case the you can guarantee that your constexpr function will never be called at runtime. In that case you can just force a non constant evaluation error.

int assert_failed() {
    static int i = 5;
    return i++;
}
constexpr int cheap_assert(bool i) {
    return i == 1 ? 0 : assert_failed();
}

constexpr unsigned operator""_my_literal(const char* s, std::size_t size) {
    return cheap_assert(size < 10), 0;
}

Upvotes: 2

Related Questions