Namespaces
Variants

std:: type_identity

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

type_identity
(C++20)
(C++11)
(C++17)
Compile-time rational arithmetic
Compile-time integer sequences
定义于头文件 <type_traits>
template < class T >
struct type_identity ;
(C++20 起)

提供成员类型定义 type ,该定义命名 T (即恒等变换)。

如果程序为 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; };

注解

std::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';  // 正常:调用 bar<double>
}

输出:

5.2

参见

(C++20)
返回其参数不变的可调用对象
(类)