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
相关推荐
南郁3 小时前
007-nlohmann/json 项目应用-C++开源库108杰
c++·开源·json·nlohmann·现代c++·d2school·108杰
菠萝015 小时前
共识算法Raft系列(1)——什么是Raft?
c++·后端·算法·区块链·共识算法
海棠蚀omo5 小时前
C++笔记-C++11(一)
开发语言·c++·笔记
凌佚6 小时前
rknn优化教程(一)
c++·目标检测·性能优化
Lenyiin8 小时前
《 C++ 点滴漫谈: 四十 》文本的艺术:C++ 正则表达式的高效应用之道
c++·正则表达式·lenyiin
yxc_inspire10 小时前
基于Qt的app开发第十三天
c++·qt·app·tcp·面向对象
虾球xz10 小时前
CppCon 2015 学习:Concurrency TS Editor’s Report
开发语言·c++·学习
潇-xiao10 小时前
Qt 按钮类控件(Push Button 与 Radio Button)(1)
c++·qt
板鸭〈小号〉10 小时前
命名管道实现本地通信
开发语言·c++
YKPG12 小时前
C++学习-入门到精通【14】标准库算法
c++·学习·算法