C++标准模板(STL)- 类型支持 (类型修改,从给定类型移除引用,std::remove_reference)

类型特性

类型特性定义一个编译时基于模板的结构,以查询或修改类型的属性。

试图特化定义于 <type_traits> 头文件的模板导致未定义行为,除了 std::common_type 可依照其所描述特化。

定义于<type_traits>头文件的模板可以用不完整类型实例化,除非另外有指定,尽管通常禁止以不完整类型实例化标准库模板。

类型修改

类型修改模板通过应用修改到模板参数,创建新类型定义。结果类型可以通过成员 typedef type 访问。

从给定类型移除引用

|------------------------------------------------|---|-----------|
| template< class T > struct remove_reference; | | (C++11 起) |

若类型 T 为引用类型,则提供成员 typedef type ,其为 T 所引用的类型。否则 typeT

成员类型

|--------|------------------------------|
| 名称 | 定义 |
| type | T 所引用的类型,或若 T 不是引用则为 T |

辅助类型

|----------------------------------------------------------------------------------------|---|-----------|
| template< class T > using remove_reference_t = typename remove_reference<T>::type; | | (C++14 起) |

可能的实现

复制代码
template< class T > struct remove_reference      {typedef T type;};
template< class T > struct remove_reference<T&>  {typedef T type;};
template< class T > struct remove_reference<T&&> {typedef T type;};

调用示例

复制代码
#include <iostream>
#include <type_traits>

int main()
{
    std::cout << std::boolalpha;
    std::cout << "std::is_same<int, int>():         "
              << std::is_same<int, int>() << std::endl;
    std::cout << "std::is_same<int, int &>():       "
              << std::is_same<int, int &>() << std::endl;
    std::cout << "std::is_same<int, int && >():     "
              << std::is_same < int, int && > () << std::endl;

    std::cout << "std::is_same<int, std::remove_reference<int>::type>():        "
              << std::is_same<int, std::remove_reference<int>::type>() << std::endl;
    std::cout << "std::is_same<int, std::remove_reference<int &>::type>()>():   "
              << std::is_same<int, std::remove_reference<int &>::type>() << std::endl;
    std::cout << "std::is_same<int, std::remove_reference < int && >::type>():  "
              << std::is_same < int, std::remove_reference < int && >::type > () << std::endl;

    return 0;
}

输出

复制代码
std::is_same<int, int>():         true
std::is_same<int, int &>():       false
std::is_same<int, int && >():     false
std::is_same<int, std::remove_reference<int>::type>():        true
std::is_same<int, std::remove_reference<int &>::type>()>():   true
std::is_same<int, std::remove_reference < int && >::type>():  true
相关推荐
吴_知遇35 分钟前
【华为OD机试真题】428、连续字母长度 | 机试真题+思路参考+代码解析(E卷)(C++)
开发语言·c++·华为od
LaoWaiHang1 小时前
MFC案例:使用键盘按键放大、缩小窗口图像的实验
c++·mfc
到底怎么取名字不会重复1 小时前
Day10——LeetCode15&560
c++·算法·leetcode·哈希算法·散列表
陈大大陈2 小时前
基于 C++ 的用户认证系统开发:从注册登录到Redis 缓存优化
java·linux·开发语言·数据结构·c++·算法·缓存
纪元A梦2 小时前
华为OD机试真题——通过软盘拷贝文件(2025A卷:200分)Java/python/JavaScript/C++/C语言/GO六种最佳实现
java·javascript·c++·python·华为od·go·华为od机试题
刚入坑的新人编程3 小时前
C++多态
开发语言·c++
QUST-Learn3D3 小时前
高精度并行2D圆弧拟合(C++)
开发语言·c++
明月醉窗台3 小时前
Qt 入门 6 之布局管理
c语言·开发语言·c++·qt
云小逸4 小时前
【C++】继承
开发语言·c++
努力学习的小廉4 小时前
【C++】 —— 笔试刷题day_21
开发语言·c++·算法