std::type_identity

< cpp‎ | types
定义于头文件 <type_traits>
template< class T >
struct type_identity;
(C++20 起)

提供指名 T 的成员 typedef type (即恒等变换)。

添加 type_identity 的特化的程序行为未定义。

成员类型

名称 定义
type T

辅助类型

template< class T >
using type_identity_t = typename type_identity<T>::type;
(C++20 起)

可能的实现

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

注解

type_identity 能用于在模板实参推导中建立非推导语境

template<class T>
void f(T, T);
 
template<class T>
void g(T, std::type_identity_t<T>);
 
f(4.2, 0); // 错误:对 'T' 推导出冲突的类型
g(4.2, 0); // OK :调用 g<double>

示例

#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