std::type_identity - cppreference.com
来自cppreference.com
template< class T > struct type_identity; |
(C++20 起) | |
提供指名 T 的成员 typedef type(即恒等变换)。
如果程序添加了 std::type_identity 的特化,那么行为未定义。
成员类型
辅助类型
template< class T > using type_identity_t = type_identity<T>::type; |
(C++20 起) | |
可能的实现
template<class T> struct type_identity { using type = T; };
注解
type_identity 能用于在模板实参推导中建立不推导语境。
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_type_identity |
201806L |
(C++20) | std::type_identity
|
示例
#include <iostream> #include <type_traits> template<class T> T foo(T a, T b) { return a + b; } template<class T> T bar(T a, std::type_identity_t<T> b) { return a + b; } int main() { // foo(4.2, 1); // 错误:对 'T' 推导的类型冲突 std::cout << bar(4.2, 1) << '\n'; // OK:调用 bar<double> }
输出: