Evgenii Legotckoi
Evgenii LegotckoiJan. 2, 2018, 3:33 p.m.

C ++ - Tutorial 012. static_assert, checking for errors at compile time

Content

Exceptions are thrown during the execution of the program; if the error can be found at compile time, you can use static_assert , which tells you to correct the program code in key locations.

The use of static_assert will look like this.

static_assert(4<=sizeof(int), "integers are too small"); // checking the size of an integer

The syntax is as follows: static_assert(A, B); Where

  • A - this is the condition under which the error will be thrown in the event that A is false
  • B - this is the text of the error message

Using

static_assert can be useful when using constants and constant expressions that are evaluated at compile time.

This code checks the local constant rate, which can not be faster than the speed of light.

constexpr double C = 299792.458; // km/s, speed of light

void f(double speed)
{
    const double local_max = 160.0/(60∗60); // 160 km/h == 160.0/(60*60) km/s
    static_assert(speed<C,"can't go that fast"); // error: speed must be a constant
    static_assert(local_max<C,"Can not move faster"); // OK
}

You can also use this check at key locations for transfers. For example, such an enumeration is given.

enum Types
{
    E_BEGIN_TYPES,
        E_A = E_BEGIN_TYPES,
        E_B,
        E_C,
        E_D,
    E_END_TYPES = E_D
};

And there is the following method or function in some place code

QString getStandardMessage(Types type)
{
    static_assert(E_END_TYPES == 3, "Need to implement method for new type");

    switch (type)
    {
        case E_A: return "Type A";
        case E_B: return "Type B";
        case E_C: return "Type C";
        case E_D: return "Type D";
        default: return "Type is not implemented";
    }
}

In this case, we know that the most recent enumeration, that is, E_D or E_END_TYPES is equal to 3. And an exception at compile time will not be thrown. But as soon as a new member of this enumeration is added.

enum Types
{
    E_BEGIN_TYPES,
        E_A = E_BEGIN_TYPES,
        E_B,
        E_C,
        E_D,
        E_E, // Новый участник перечисления
    E_END_TYPES = E_E
};

That static_assert will throw an error, which will mean that we forgot to correct this method. Correction will look like this.

QString getStandardMessage(Types type)
{
    static_assert(E_END_TYPES == 4, "Need to implement method for new type");

    switch (type)
    {
        case E_A: return "Type A";
        case E_B: return "Type B";
        case E_C: return "Type C";
        case E_D: return "Type D";
        case E_E: return "Type E";
        default: return "Type is not implemented";
    }
}

In this method, we add the implementation of the code for type E_E , and also correct the static_assert itself, so that it takes into account the number of enumeration participants with the new participant.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Ua

Qt - Test 001. Signals and slots

  • Result:84points,
  • Rating points4
Ua

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
ОК

Qt - Test 001. Signals and slots

  • Result:47points,
  • Rating points-6
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 9:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 11:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 5:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 4:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 8:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
f
firstlunoxodFeb. 15, 2025, 1:46 p.m.
Рисование на QGraphicsScene при зажатой кнопке мыши Подскажите, пожалуйста! Как данный класс можно дополнить, чтобы созданные объекты можно было перемещать мышкой по сцене?
Дмитрий
ДмитрийFeb. 3, 2025, 4:24 p.m.
Создание deb-пакета. Как создать ярлык на рабочем столе после установки собственного deb-пакета? Всем привет. Сделал свой deb-пакет с программой. Всё устанавливается и работает. Ставлю по пути /usr/bin/my_application. Как для пользователя при установке пакета сразу создать ярлык на раб…
NW
Nayo WaiJan. 30, 2025, 7:22 p.m.
не запускается компьютер!!! Не запускается компьютер (точнее работает блок , но сам монитор вообще жесть)В общем я ничего с интернета не скачивала в последнее время. На компе никаких левых пр…
n
nklyJan. 3, 2025, 12:52 p.m.
Нужно запретить перемещение только некоторых итемов, остальные перемещать можно. Вопрос решен. Узнать QModelIndex элемента на который мы перетаскиваем другой элемент, можно с помощью функции indexAt(event->position().toPoint()) представления QTreeViev вызываемой в переопр…
M
MarselAug. 17, 2023, 12:26 a.m.
OAuth2.0 через VK, получение email Спасибо большое за помощь и простите за то что отнял время своей невнимательностью.

Follow us in social networks