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
相关推荐
Charles Ray33 分钟前
C++学习笔记 —— 内存分配 new
c++·笔记·学习
重生之我在20年代敲代码33 分钟前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
迷迭所归处6 小时前
C++ —— 关于vector
开发语言·c++·算法
CV工程师小林7 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
white__ice8 小时前
2024.9.19
c++
天玑y8 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
姜太公钓鲸2338 小时前
c++ static(详解)
开发语言·c++
菜菜想进步8 小时前
内存管理(C++版)
c语言·开发语言·c++
Joker100858 小时前
C++初阶学习——探索STL奥秘——模拟实现list类
c++
科研小白_d.s8 小时前
vscode配置c/c++环境
c语言·c++·vscode