1

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:

  • static_assert is not allowed because the inputs could be run time values
  • assert may force the function to be run time evaluated and the assert handler drags in so much stuff that it will overflow the flash memory of most Cortex chips
  • throw will not work because I turned off exceptions

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.

Community
  • 1
  • 1
odinthenerd
  • 5,422
  • 1
  • 32
  • 61
  • 2
    http://stackoverflow.com/questions/30437431/is-assert-usable-in-constant-expressions – Columbo Feb 03 '16 at 19:50
  • In C++14 you're allowed to `assert` in `constexpr` functions. – 101010 Feb 03 '16 at 19:53
  • @101010 thanks for the comment, I need it on C++11 though, added that to my question – odinthenerd Feb 03 '16 at 20:08
  • @columbo thanks for the link, looks like my question may be a duplicate – odinthenerd Feb 03 '16 at 20:09
  • looks like assert is also not an option because the GCC assert drags so much stuff into the binary that I would not fit on most ARM Cortex chips – odinthenerd Feb 03 '16 at 20:22
  • How do you "assert"-equivalent in a non-constexpr function on your platform? It isn't *that* hard to convert almost any runtime handler to a `constexpr`-conditionally-safe one, but without a solution for non-`constexpr` I'm not sure what you expect. – Yakk - Adam Nevraumont Feb 03 '16 at 20:26
  • "assert"-equivalent is calling a hard fault handler who's functionality is customizeable but usually triggers a breakpoint or resets the system. Thats why I would rather push the error to compile time. – odinthenerd Feb 03 '16 at 21:40

1 Answers1

2

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;
}
odinthenerd
  • 5,422
  • 1
  • 32
  • 61