C++中的类型推断(auto 和 decltype)

news/2024/10/17 10:24:55/

类型推断 是指在编程语言中自动推导表达式的数据类型。在C++11之前,每个数据类型都需要在编译时显示声明,在运行时限制表达式的值,但在C++的新版本之后,引入了 auto 和 decltype等关键字,这允许程序员将类型推导留给了编译器本身。

有了类型推断功能,我们必须耗费时间去写编译器已经知道的东西。由于所有类型仅在编译器阶段推导,因此编译时间略有增加,但不会影响程序的运行时间。

1. C++中的auto

C++中的 auto 关键字指定要声明的变量的类型根据其初始值自动推导。如果函数的返回类型是auto,那么它将在运行时由返回类型表达式确定类型。auto的良好用途是在为容器创建迭代器时避免冗长的初始化。

注意:使用auto关键字声明的变量应仅在声明时初始化,否则将出现编译时错误。

C++中auto例子

// C++ program to demonstrate working of auto
// and type inference#include <bits/stdc++.h>
using namespace std;int main()
{// auto a; this line will give error// because 'a' is not initialized at// the time of declaration// a=33;// see here x ,y,ptr are// initialised at the time of// declaration hence there is// no error in themauto x = 4;auto y = 3.37;auto z = 3.37f;auto c = 'a';auto ptr = &x;auto pptr = &ptr; //pointer to a pointercout << typeid(x).name() << endl<< typeid(y).name() << endl<< typeid(z).name() << endl<< typeid(c).name() << endl<< typeid(ptr).name() << endl<< typeid(pptr).name() << endl;return 0;
}

输出

i
d
f
c
Pi
PPi

注意:我们使用了 typeid 来获取变量的类型。

这里,typeid是一个运算符,用于获取需要对象的动态类型。

typeid(x).name() 返回 x 的数据类型,例如,它返回:

  • i 表整数integer,d 表 doubles
  • f 表 float,cchar
  • Pi 表指向整数的指针
  • Pd 表示指向double的指针
  • Pc 表示指向 char 的指针
  • PPi 表示指向整数的指针的指针
  • 单指针前缀 P
  • 双指针用 PP 作为前缀,以此类推

但实际返回的名称主要取决于编译器。

注意:auto的良好用途是在为容器创建迭代器时避免冗长的初始化。

C++ auto关键字例子

// C++ program to demonstrate that we can use auto to
// save time when creating iterators#include <bits/stdc++.h>
using namespace std;int main()
{// Create a set of stringsset<string> st;st.insert({ "geeks", "for", "geeks", "org" });// 'it' evaluates to iterator to set of string// type automaticallyfor (auto it = st.begin(); it != st.end(); it++)cout << *it << " ";return 0;
}

输出

for geeks org 

注意:如果给auto赋值一个整型引用,它也会变成整型。要使其成为引用类型,我们使用auto &。

  • 返回整数引用类型的函数:int& fun() {};
  • m 会默认为 int类型而不是 int&类型:auto m = fun();
  • n 将是 int& 类型因为使用了auto &:auto& n = fun();

2. C++中的decltype

在C++中,decltype关键字可以检查实体声明的类型或表达式的类型。‘auto’ 允许你声明具有特定类型的变量,而decltype允许你从变量中提取类型,所以decltype是一种计算传递表达式类型的操作符。

下面解释上述关键字及其用途:

例子

// C++ program to demonstrate use of decltype
#include <bits/stdc++.h>
using namespace std;int fun1() { return 10; }
char fun2() { return 'g'; }int main()
{// Data type of x is same as return type of fun1()// and type of y is same as return type of fun2()decltype(fun1()) x;decltype(fun2()) y;cout << typeid(x).name() << endl;cout << typeid(y).name() << endl;return 0;
}

输出

i
c

以下是演示decltype的使用的又一个示例,

// C++ program to demonstrate use of decltype
#include <bits/stdc++.h>
using namespace std;// Driver Code
int main()
{int x = 5;// j will be of type int : data type of xdecltype(x) j = x + 5;cout << typeid(j).name();return 0;
}

输出

i

示例:演示auto和decltype的使用的C++程序

下面是一个C++模板函数min_type(),它返回两个数字中的最小值。这两个数字可以是任何整数类型。返回类型是由两者中的最小值来确定的。

// C++ program to demonstrate use of decltype in functions
#include <bits/stdc++.h>
using namespace std;// A generic function which finds minimum of two values
// return type is type of variable which is minimum
template <class A, class B>
auto findMin(A a, B b) -> decltype(a < b ? a : b)
{return (a < b) ? a : b;
}// driver function to test various inference
int main()
{// This call returns 3.44 of double typecout << findMin(4, 3.44) << endl;// This call returns 3 of double typecout << findMin(5.4, 3) << endl;return 0;
}

输出:

3.44
3

decltype vs typeid

以下是decltype和typeid之间的一些主要区别

  • decltype在编译时提供类型信息,而typeid在运行时提供。
  • 因此,如果我们有一个基类引用(或指针)引用(或指向)一个派生类对象,decltype会将类型作为基类引用(或者指针),但typeid会将类型作为派生类引用(或者指针)。

http://www.ppmy.cn/news/1283277.html

相关文章

LSTM和GRU vs 循环神经网络RNN

1、考虑下列三种情况下&#xff0c;对比一下普通RNN的表现和LSTM和GRU表现&#xff1a; &#xff08;1&#xff09;早期观测值对预测未来观测者具有非常重要的意义。 考虑一个极端情况&#xff0c;其中第一个观测值包含一个校验和&#xff0c; 目标是在序列的末尾辨别校验和是…

微信小程序预览pdf,修改pdf文件名

记录微信小程序预览pdf文件&#xff0c;修改pdf名字安卓和ios都可用。 1.安卓和苹果的效果 2.需要用到的api 1.wx.downloadFile wx.downloadFile 下载文件资源到本地。客户端直接发起一个 HTTPS GET 请求&#xff0c;返回文件的本地临时路径 (本地路径)&#xff0c;单次下载…

低代码选型注意事项

凭借着革命性的生产力优势&#xff0c;低代码技术火爆了整个IT圈。面对纷繁复杂的低代码和无代码产品&#xff0c;开发者该如何选择&#xff1f; 在研究低代码平台的年数上&#xff0c;本人已有3年&#xff0c;也算是个低代码资深用户了&#xff0c;很多企业面临低代码选型上的…

七功能遥控编解码芯片

一、基本概述 TT6/TR6 是一对为遥控玩具车设计的 CMOS LSI 芯片。TT6 为发射编码芯片&#xff0c;TR6 为接收解码芯片。TT6/TR6 提供七个功能按键控制前进、后退、左转、右转、加速、独立功能 F1,独立功能 F2 的动作。除此以外&#xff0c;还有这五种常规小车功能&#xff08;…

【赠书第13期】边缘计算系统设计与实践

文章目录 前言 1 硬件架构设计 2 软件框架设计 3 网络结构设计 4 安全性、可扩展性和性能优化 5 推荐图书 6 粉丝福利 前言 边缘计算是一种新兴的计算模式&#xff0c;它将计算资源推向网络边缘&#xff0c;以更好地满足实时性、低延迟和大规模设备连接的需求。边缘计算…

【zookeeper特点和集群架构】

文章目录 1. Zookeeper介绍2、ZooKeeper数据结构3、Zookeeper集群架构 1. Zookeeper介绍 ZooKeeper 是一个开源的分布式协调框架&#xff0c;是Apache Hadoop 的一个子项目&#xff0c;主要用来解决分 布式集群中应用系统的一致性问题。Zookeeper 的设计目标是将那些复杂且容易…

LeetCode——动态规划

动态规划 一、一维数组&#xff1a;斐波那契数列 爬楼梯70简单 dp定义&#xff1a; dp[i]表示爬到第i阶有多少种不同的方式 状态转移方程&#xff1a; dp[i] dp[i-1] dp[i-1] &#xff08;每次可以爬1或2个台阶&#xff09; 边界条件&#xff1a; dp[0] 1; dp[1] 1;&#…

最佳实践!Apipost使用指南

自诞生以来&#xff0c;Apipost凭借其简洁直观的用户界面、强大的功能以及简单、易上手的操作&#xff0c;让Apipost成为了开发人员不可或缺的工具。本文将详细介绍Apipost的主要功能和使用方法&#xff0c;帮助大家更好地了解这款优秀的API开发工具。 下载安装 直接进入Apip…