CPP_GEEK Telegram 334
Полезные функции, которые будут полезны продвинутым C++ разработчикам.

1. void assert_or_throw(bool cond, const std::string& msg)

Универсальная замена assert в runtime-среде:


void assert_or_throw(bool cond, const std::string& msg) {
if (!cond) throw std::runtime_error(msg);
}



2. template<typename T> std::string to_string_precise(const T& val, int precision = 6)

Преобразование чисел с точностью:


template<typename T>
std::string to_string_precise(const T& val, int precision = 6) {
std::ostringstream out;
out << std::fixed << std::setprecision(precision) << val;
return out.str();
}



3. template<typename F> auto scope_exit(F&& f)

RAII-функция для отложенного вызова:


template<typename F>
class ScopeExit {
F func;
bool active = true;
public:
ScopeExit(F&& f) : func(std::forward<F>(f)) {}
~ScopeExit() { if (active) func(); }
void dismiss() { active = false; }
};

template<typename F>
ScopeExit<F> scope_exit(F&& f) {
return ScopeExit<F>(std::forward<F>(f));
}



4. template<typename T> constexpr bool is_power_of_two(T x)

Компилируемая проверка степени двойки:


template<typename T>
constexpr bool is_power_of_two(T x) {
return x > 0 && (x & (x - 1)) == 0;
}



5. template<typename T> void hash_combine(std::size_t& seed, const T& val)

Для реализации собственного std::hash:


template<typename T>
void hash_combine(std::size_t& seed, const T& val) {
seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}



6. std::vector<std::string> split(const std::string& str, char delimiter)

Полезна для парсинга CSV, логов и т.д.:


std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> out;
std::istringstream ss(str);
std::string token;
while (std::getline(ss, token, delimiter)) {
out.push_back(token);
}
return out;
}



7. template<typename T> T clamp(T val, T min_val, T max_val)

Ручной аналог std::clamp (если нужна совместимость со старым C++):


template<typename T>
T clamp(T val, T min_val, T max_val) {
return std::max(min_val, std::min(val, max_val));
}



8. template<typename Container, typename Predicate> bool any_of(const Container& c, Predicate pred)

Упрощённая обёртка над std::any_of:


template<typename Container, typename Predicate>
bool any_of(const Container& c, Predicate pred) {
return std::any_of(c.begin(), c.end(), pred);
}



9. template<typename... Args> std::string format(const std::string& fmt, Args&&... args)

Интерфейс к std::format (C++20+):


template<typename... Args>
std::string format(const std::string& fmt, Args&&... args) {
return std::vformat(fmt, std::make_format_args(args...));
}



10. template<typename T> std::string type_name()

Получение имени типа на этапе компиляции:


template<typename T>
std::string type_name() {
#ifdef __clang__
std::string name = __PRETTY_FUNCTION__;
return name.substr(31, name.length() - 32);
#elif defined(__GNUC__)
std::string name = __PRETTY_FUNCTION__;
return name.substr(49, name.length() - 50);
#elif defined(_MSC_VER)
std::string name = __FUNCSIG__;
return name.substr(38, name.length() - 45);
#else
return "unknown";
#endif
}


➡️ @cpp_geek
👍92



tgoop.com/cpp_geek/334
Create:
Last Update:

Полезные функции, которые будут полезны продвинутым C++ разработчикам.

1. void assert_or_throw(bool cond, const std::string& msg)

Универсальная замена assert в runtime-среде:


void assert_or_throw(bool cond, const std::string& msg) {
if (!cond) throw std::runtime_error(msg);
}



2. template<typename T> std::string to_string_precise(const T& val, int precision = 6)

Преобразование чисел с точностью:


template<typename T>
std::string to_string_precise(const T& val, int precision = 6) {
std::ostringstream out;
out << std::fixed << std::setprecision(precision) << val;
return out.str();
}



3. template<typename F> auto scope_exit(F&& f)

RAII-функция для отложенного вызова:


template<typename F>
class ScopeExit {
F func;
bool active = true;
public:
ScopeExit(F&& f) : func(std::forward<F>(f)) {}
~ScopeExit() { if (active) func(); }
void dismiss() { active = false; }
};

template<typename F>
ScopeExit<F> scope_exit(F&& f) {
return ScopeExit<F>(std::forward<F>(f));
}



4. template<typename T> constexpr bool is_power_of_two(T x)

Компилируемая проверка степени двойки:


template<typename T>
constexpr bool is_power_of_two(T x) {
return x > 0 && (x & (x - 1)) == 0;
}



5. template<typename T> void hash_combine(std::size_t& seed, const T& val)

Для реализации собственного std::hash:


template<typename T>
void hash_combine(std::size_t& seed, const T& val) {
seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}



6. std::vector<std::string> split(const std::string& str, char delimiter)

Полезна для парсинга CSV, логов и т.д.:


std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> out;
std::istringstream ss(str);
std::string token;
while (std::getline(ss, token, delimiter)) {
out.push_back(token);
}
return out;
}



7. template<typename T> T clamp(T val, T min_val, T max_val)

Ручной аналог std::clamp (если нужна совместимость со старым C++):


template<typename T>
T clamp(T val, T min_val, T max_val) {
return std::max(min_val, std::min(val, max_val));
}



8. template<typename Container, typename Predicate> bool any_of(const Container& c, Predicate pred)

Упрощённая обёртка над std::any_of:


template<typename Container, typename Predicate>
bool any_of(const Container& c, Predicate pred) {
return std::any_of(c.begin(), c.end(), pred);
}



9. template<typename... Args> std::string format(const std::string& fmt, Args&&... args)

Интерфейс к std::format (C++20+):


template<typename... Args>
std::string format(const std::string& fmt, Args&&... args) {
return std::vformat(fmt, std::make_format_args(args...));
}



10. template<typename T> std::string type_name()

Получение имени типа на этапе компиляции:


template<typename T>
std::string type_name() {
#ifdef __clang__
std::string name = __PRETTY_FUNCTION__;
return name.substr(31, name.length() - 32);
#elif defined(__GNUC__)
std::string name = __PRETTY_FUNCTION__;
return name.substr(49, name.length() - 50);
#elif defined(_MSC_VER)
std::string name = __FUNCSIG__;
return name.substr(38, name.length() - 45);
#else
return "unknown";
#endif
}


➡️ @cpp_geek

BY C++ geek


Share with your friend now:
tgoop.com/cpp_geek/334

View MORE
Open in Telegram


Telegram News

Date: |

Matt Hussey, editorial director of NEAR Protocol (and former editor-in-chief of Decrypt) responded to the news of the Telegram group with “#meIRL.” Telegram has announced a number of measures aiming to tackle the spread of disinformation through its platform in Brazil. These features are part of an agreement between the platform and the country's authorities ahead of the elections in October. The court said the defendant had also incited people to commit public nuisance, with messages calling on them to take part in rallies and demonstrations including at Hong Kong International Airport, to block roads and to paralyse the public transportation system. Various forms of protest promoted on the messaging platform included general strikes, lunchtime protests and silent sit-ins. Just at this time, Bitcoin and the broader crypto market have dropped to new 2022 lows. The Bitcoin price has tanked 10 percent dropping to $20,000. On the other hand, the altcoin space is witnessing even more brutal correction. Bitcoin has dropped nearly 60 percent year-to-date and more than 70 percent since its all-time high in November 2021. 1What is Telegram Channels?
from us


Telegram C++ geek
FROM American