Telegram Group & Telegram Channel
Как упростить дебаг через std::format и std::source_location

Когда вы отлаживаете сложный баг, бывает сложно быстро понять, где и почему произошла ошибка. С C++20 стало гораздо проще автоматизировать логирование и сделать его по-настоящему информативным.

Вот пример:


#include <iostream>
#include <format>
#include <source_location>

void log(const std::string& message,
const std::source_location location = std::source_location::current())
{
std::cout << std::format("[{}:{} - {}] {}\n",
location.file_name(),
location.line(),
location.function_name(),
message);
}

int divide(int a, int b)
{
if (b == 0) {
log("Попытка деления на ноль");
return 0;
}
return a / b;
}


📌 Этот код выведет:


[main.cpp:16 - divide] Попытка деления на ноль


Вы больше не пишете руками __FILE__, __LINE__ и __func__. Всё это делает std::source_location. А с std::format — красиво и читаемо.

➡️ @cpp_geek



tg-me.com/cpp_geek/293
Create:
Last Update:

Как упростить дебаг через std::format и std::source_location

Когда вы отлаживаете сложный баг, бывает сложно быстро понять, где и почему произошла ошибка. С C++20 стало гораздо проще автоматизировать логирование и сделать его по-настоящему информативным.

Вот пример:


#include <iostream>
#include <format>
#include <source_location>

void log(const std::string& message,
const std::source_location location = std::source_location::current())
{
std::cout << std::format("[{}:{} - {}] {}\n",
location.file_name(),
location.line(),
location.function_name(),
message);
}

int divide(int a, int b)
{
if (b == 0) {
log("Попытка деления на ноль");
return 0;
}
return a / b;
}


📌 Этот код выведет:


[main.cpp:16 - divide] Попытка деления на ноль


Вы больше не пишете руками __FILE__, __LINE__ и __func__. Всё это делает std::source_location. А с std::format — красиво и читаемо.

➡️ @cpp_geek

BY C++ geek




Share with your friend now:
tg-me.com/cpp_geek/293

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

The S&P 500 slumped 1.8% on Monday and Tuesday, thanks to China Evergrande, the Chinese property company that looks like it is ready to default on its more-than $300 billion in debt. Cries of the next Lehman Brothers—or maybe the next Silverado?—echoed through the canyons of Wall Street as investors prepared for the worst.

What is Telegram Possible Future Strategies?

Cryptoassets enthusiasts use this application for their trade activities, and they may make donations for this cause.If somehow Telegram do run out of money to sustain themselves they will probably introduce some features that will not hinder the rudimentary principle of Telegram but provide users with enhanced and enriched experience. This could be similar to features where characters can be customized in a game which directly do not affect the in-game strategies but add to the experience.

telegram from sg


Telegram C++ geek
FROM USA