std::type_identity
来自cppreference.com
在标头 <type_traits> 定义 | ||
template<class T > struct type_identity; | (C++20 起) | |
提供指名 T
的成员 typedef type
(即恒等变换)。
如果程序添加了 std::type_identity
的特化,那么行为未定义。
目录 |
[编辑]成员类型
名称 | 定义 |
type | T |
[编辑]辅助类型
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>}
输出:
5.2
[编辑]参阅
(C++20) | 返回其未修改的实参的函数对象 (类) |