CPPPROGLIB Telegram 6084
🌻 std::type_identity — предотвращение template argument deduction

Если нужно запретить автоматический вывод типов для некоторых параметров шаблона, то std::type_identity поможет решить эту проблему.

std::type_identity из C++20 — простая обертка, которая предотвращает template argument deduction. Полезно для создания non-deduced contexts.


👉 Определение:
template<typename T>
struct type_identity { using type = T; };

template<typename T>
using type_identity_t = typename type_identity<T>::type;



💡 Примеры использования:
// БЕЗ type_identity - тип T выводится автоматически
template<typename T>
void convert_and_print(T from, T to) { /* ... */ }

convert_and_print(1, 2.5); // Ошибка: T не может быть int и double

// С type_identity - принуждаем указать тип явно
template<typename T>
void convert_and_print(T from, std::type_identity_t<T> to) {
std::cout << static_cast<T>(to) << std::endl;
}

convert_and_print<double>(1, 2.5); // OK: T = double}



💡 Функции сравнения:
template<typename T>
bool equal(const T& a, std::type_identity_t<const T&> b) {
return a == b;
}

std::string str = "hello";
equal(str, "hello"); // OK: T = std::string, второй параметр - const char*



🔍 Factory с явным указанием типа:
template<typename T>
std::unique_ptr<T> make_initialized(std::type_identity_t<T> init_value) {
return std::make_unique<T>(init_value);
}

// Тип нужно указать явно
auto ptr = make_initialized<std::string>("Hello World");


Библиотека C/C++ разработчика

#буст
Please open Telegram to view this post
VIEW IN TELEGRAM
10👍4



tgoop.com/cppproglib/6084
Create:
Last Update:

🌻 std::type_identity — предотвращение template argument deduction

Если нужно запретить автоматический вывод типов для некоторых параметров шаблона, то std::type_identity поможет решить эту проблему.

std::type_identity из C++20 — простая обертка, которая предотвращает template argument deduction. Полезно для создания non-deduced contexts.


👉 Определение:

template<typename T>
struct type_identity { using type = T; };

template<typename T>
using type_identity_t = typename type_identity<T>::type;



💡 Примеры использования:
// БЕЗ type_identity - тип T выводится автоматически
template<typename T>
void convert_and_print(T from, T to) { /* ... */ }

convert_and_print(1, 2.5); // Ошибка: T не может быть int и double

// С type_identity - принуждаем указать тип явно
template<typename T>
void convert_and_print(T from, std::type_identity_t<T> to) {
std::cout << static_cast<T>(to) << std::endl;
}

convert_and_print<double>(1, 2.5); // OK: T = double}



💡 Функции сравнения:
template<typename T>
bool equal(const T& a, std::type_identity_t<const T&> b) {
return a == b;
}

std::string str = "hello";
equal(str, "hello"); // OK: T = std::string, второй параметр - const char*



🔍 Factory с явным указанием типа:
template<typename T>
std::unique_ptr<T> make_initialized(std::type_identity_t<T> init_value) {
return std::make_unique<T>(init_value);
}

// Тип нужно указать явно
auto ptr = make_initialized<std::string>("Hello World");


Библиотека C/C++ разработчика

#буст

BY Библиотека C/C++ разработчика | cpp, boost, qt


Share with your friend now:
tgoop.com/cppproglib/6084

View MORE
Open in Telegram


Telegram News

Date: |

Choose quality over quantity. Remember that one high-quality post is better than five short publications of questionable value. fire bomb molotov November 18 Dylan Hollingsworth yau ma tei 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. Although some crypto traders have moved toward screaming as a coping mechanism, several mental health experts call this therapy a pseudoscience. The crypto community finds its way to engage in one or the other way and share its feelings with other fellow members. Concise
from us


Telegram Библиотека C/C++ разработчика | cpp, boost, qt
FROM American