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
相关推荐
醉城夜风~16 分钟前
(超详细)C++多态(Polymorphism)
开发语言·c++
小小龙学IT36 分钟前
现代 C++ 内存管理与资源安全深度解析:从 RAII 到所有权模型
c++·安全
欧特克_Glodon1 小时前
OpenCV计算机视觉开发入门与实践<十三>:图像转换之灰度图、二值图
c++·人工智能·opencv·计算机视觉
神仙别闹1 小时前
基于C++ MFC实现动态分区分配存储管理
开发语言·c++·mfc
skr爱码士1 小时前
03_第一个Qt项目:Hello World 的完整拆解
c++·qt·客户端
欧特克_Glodon1 小时前
OpenCV计算机视觉开发入门与实践<十二>:XML 和 YAML 文件读写
xml·c++·opencv·计算机视觉
ryanuo71 小时前
Shadcn/ui × Qt 6/QML:一次从 Web UI 到桌面 UI 的组件化实践
c++·qt·ui·shadcn
余额瞒着我当琳1 小时前
C++--vector第二讲:手写 C++ STL:vector 源码剖析与迭代器失效分析
android·java·c++
郝学胜-神的一滴1 小时前
[简化版 GAMES 104] 现代游戏引擎 06:从Tick时序到邮局模型,拆解确定性世界的底层密码
开发语言·c++·游戏引擎·图形渲染·软件开发·opengl
不会代码的小猴1 小时前
6. Qt网络编程
开发语言·c++·笔记·qt·算法