V
V
Vadim Deryabkin2017-06-19 18:39:37
Debugging
Vadim Deryabkin, 2017-06-19 18:39:37

How to display an error message from a constexpr function and abort compilation (C++1y; C++14)?

There is some constexpr function that checks the parameters of the input structure. If some parameter is set incorrectly, you need to display an error message with the most detailed log.
For these purposes, it would be convenient to use printf or something similar, but all these methods are prohibited in constexpr. Now I use the following method:

constexpr const pll_cfg* rcc::pll_main_configuration_check ( const pll_cfg* const cfg, uint8_t count ) {
    // Проверяем все имеющиеся структуры конфигурации основного PLL.
    for ( int loop = 0; loop < count; loop++ ) {
        // Ошибка в одной из структур pll_cfg, параметр M.
        if ( ( cfg[loop].m < 2 ) || ( cfg[loop].m > 63 ) )
            throw("Structure has an invalid parameter M! M >= 2 and M <= 63!");

However, when using throw, it is not possible to specifically specify the number of the structure (loop variable) in which the error occurred. At most, the compiler will point to this line and issue the following message.
error: expression '<throw-expression>' is not a constant-expression

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim Deryabkin, 2017-06-23
@Vadimatorikda

The answer is formatted as an article on Habré: https://habrahabr.ru/post/331468/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question