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: |

How Does Bitcoin Mining Work?

Bitcoin mining is the process of adding new transactions to the Bitcoin blockchain. It’s a tough job. People who choose to mine Bitcoin use a process called proof of work, deploying computers in a race to solve mathematical puzzles that verify transactions.To entice miners to keep racing to solve the puzzles and support the overall system, the Bitcoin code rewards miners with new Bitcoins. “This is how new coins are created” and new transactions are added to the blockchain, says Okoro.

telegram from hk


Telegram C++ geek
FROM USA