当前位置: 首页 > news >正文

C++11新特性_自动类型推导_decltype

   decltype 是 C++11 引入的一个关键字,用于在编译时推导表达式的类型。它提供了一种方式,让编译器根据表达式的类型来确定变量的类型,而不需要显式地指定类型。下面为你详细介绍 decltype 的使用方法和应用场景。


基本语法

decltype 的基本语法如下:

decltype(expression) var;

这里的 expression 是一个表达式,decltype 会根据这个表达式的类型来推导 var 的类型。 

使用场景及示例 

1. 推导变量类型
#include <iostream>int main() {int x = 10;decltype(x) y = 20; // y 的类型被推导为 intstd::cout << typeid(y).name() << std::endl;return 0;
}

在这个例子中,decltype(x) 推导 x 的类型为 int,所以 y 的类型也被定义为 int

2. 推导函数返回值类型
#include <iostream>int add(int a, int b) {return a + b;
}int main() {decltype(add(1, 2)) result = add(3, 4); // result 的类型被推导为 intstd::cout << "Result: " << result << std::endl;return 0;
}

这里 decltype(add(1, 2)) 根据 add 函数的返回值类型推导出 result 的类型为 int

3. 用于模板编程
#include <iostream>template <typename T, typename U>
auto add(T a, U b) -> decltype(a + b) {return a + b;
}int main() {auto result = add(1, 2.5);std::cout << "Result: " << result << std::endl;return 0;
}

在这个模板函数 add 中,使用了尾随返回类型,decltype(a + b) 会根据 a 和 b 的类型推导出相加结果的类型,从而确定函数的返回类型。

4. 推导引用类型
#include <iostream>int main() {int x = 10;int& ref_x = x;decltype(ref_x) ref_y = x; // ref_y 的类型为 int&ref_y = 20;std::cout << "x: " << x << std::endl;return 0;
}

decltype(ref_x) 推导 ref_x 的类型为 int&,所以 ref_y 也是一个引用,修改 ref_y 会影响到 x

http://www.xdnf.cn/news/248041.html

相关文章:

  • Java内存对象实现聚合查询
  • Unity SpriteMask(精灵遮罩)
  • PMP-第八章 项目质量管理
  • 攻防世界 dice_game
  • 多智能体空域协同中的伦理博弈与系统调停
  • LegalOne:本土与国际视野融合的法律评级,大湾区律师及律师事务所榜单申报启动
  • 【统计方法】方差分析(ANOVA):判断数据差异的统计方法
  • 【Linux】环境基础开发工具使用
  • 26.电流信号的强抗干扰能力运用
  • 深圳第三方软件测试机构如何填补企业空缺并助力市场发展?
  • LintCode第652题-递归版
  • Linux基础指令【下】
  • Leetcode刷题报告2——双指针法
  • 基于DrissionPage的高效爬虫开发:以小说网站数据抓取为例
  • vue自定义表头内容excel表格导出
  • LangChain4j +DeepSeek大模型应用开发——7 项目实战 创建硅谷小鹿
  • SpringAI使用OpenAI API格式调用DeepSeek服务
  • 《AIStarter安装部署全攻略:AI绘画/数字人项目快速上手指南(含Windows环境配置要点)》
  • *(解引用运算符)与 ++(自增运算符)的优先级
  • 开始一个vue项目
  • 《排序算法总结》
  • 60常用控件_QSpinBox的使用
  • [FPGA Video IP] Frame Buffer Read and Write
  • 一文读懂EMC VNX存储的Fast Cache(第二部分:对比)
  • 【RocketMQ】- 源码系列目录
  • 实习入职的总结
  • 前端八股 CSS 1
  • Chromium 134 编译指南 - Android 篇:从Linux版切换到Android版(六)
  • 2025智能体的发展趋势
  • 深⼊理解指针(8)