I am looking for a way to raise a compile-time error from a constexpr function. Since I am on an embedded system, C++ exceptions need to remain disabled (GCC flag -fno-exceptions). Thus, the default way of error reporting seems to be infeasible.
A possible way described in constexpr error at compile-time, but no overhead at run-time is to call a non-constexpr function, which throws an error if compile-time implementation is forced. However, this solution gives rather unreadable error messages and the implementation is forced to return garbage return values in order to silence "control may reach end of non-void function" warnings.
Is there a better way, which allows to provide a custom error message?
Please note, that I am aware of static_assert
and the possibility to convert the function to a template. However, static_assert
needs to reassemble the quite complex logic of the switch-blocks of my use-case in order to throw an error, which is error-prone and clumsy.
Example use-case:
constexpr SpiDmaTxStreams spiDmaTxStream(DmaId dmaId, DmaStreamId streamId) {
switch (dmaId) {
case DmaId::DMA_1:
switch (streamId) {
case DmaStreamId::Stream_4:
return SpiDmaTxStreams::Dma1Stream4;
// ...
default:
break;
}
break;
case DmaId::DMA_2:
switch (streamId) {
case DmaStreamId::Stream_1:
return SpiDmaTxStreams::Dma2Stream1;
// ...
default:
break;
}
break;
}
// report compile-time error "invalid DMA-stream combination"
}