c++ decltype的使用方法

  介绍

这篇文章主要介绍”c++ decltype的使用方法”,在日常操作中,相信很多人在c++ decltype的使用方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答“c++ decltype的使用方法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1。什么是decltype ,,,,

,,,,decltype是c++ 11新增的一个关键字,和汽车的功能一样,用来在<强>编译时期强进行自动类型推导。引入decltype是因为汽车并不适用于所有的自动类型推导场景,在某些特殊情况下汽车用起来很不方便,甚至压根无法使用。

对于内置类型的对象,使用decltype很直观,但当参数为复合类型的时候就应该注意一些使用细节问题。

auto  varName=价值;   decltype (exp), varName=价值; <李>

,汽车根据=右边的初始值推导出变量的类型,decltype根据exp表达式推导出变量的类型,跟=右边的价值没有关系

<李>

汽车要求变量必须初始化,这是因为汽车根据变量的初始值来推导变量类型的,如果不初始化,变量的类型也就无法推导

<李>

而decltype不要求,因此可以写成如下形式

decltype (exp) varName;

原则上,将实验只是一个普通的表达式,它可以是任意复杂的形式,但必须保证实验的结果是有类型的,不能是无效的,如实验为一个返回值为空的函数时,实验的结果也是无效类型,此时会导致编译错误

1.1 decltype的几种形式

int  x =, 0;   decltype (x), y =, 1,,,,,,,,,,,,//, y →int   decltype(时间+ x  y), z =, 0;,,,,,,,//, z →int   const  int&,小姐:=,x;   decltype (i), j =, y,,,,,,,,,,,,//, j →, const  int 及   const  decltype (z), *, p =,, z,,,//, * p ,→, const  int,, p ,→const  int  *   decltype (z), *, pi =,, z,,,,,,,,//, * pi →, int ,,,,,,, pi →int  *   decltype(π)*,pp =,,π,,,,,,,//,* pp →, int  *,,,,,, pp →, int  *, *

2。推导规则

,,,decltype的推导规则可以简单概述如下:

<李>

如果实验是一个不被括号()包围的表达式,或者是一个类成员访问表达式,或者是一个单独的变量,decltype (exp)的类型和exp一致

<李>

如果exp是函数调用,则decltype (exp)的类型就和函数返回值的类型一致

<李>

如果实验是一个左值,或被括号()包围,decltype (exp)的类型就是exp的引,用假设exp的类型为T,则decltype (exp)的类型为T&

规则1示例:

# include,   # include   using  namespace 性传播疾病;   ,   class  {   公众:   ,,,static  int 总;   ,,,string 名称;   ,,,int 年龄;   ,,,float 成绩;   }   ,   int :总=0;   ,   int  main ()   {   int  n=0;   const  int , r=n;   A ;   decltype (n), x=n,,,,,//n为Int x被推导为Int   decltype (r), y=n,,,,,//r为const  int ,, y被推导为const  int 及   decltype(::总),,z=0;,,///总是类一个的一个int 类型的成员变量,z被推导为int   decltype (A.name), url=皐ww.baidu.com";//url为stringleix   return  0;   }

规则2示例:

int&, func1 (int  char);//返回值为int&   int&,, func2(空白);//返回值为int&及   int  func3(双);//返回值为int   ,   const  int&, func4 (int, int, int);//返回值为const  int&   const  int&,, func5(空白);//返回值为const  int&及   ,   int  n=50;   decltype (func1(100 & # 39;一个# 39;)),一个=n;//的类型为int&   decltype (func2 ()), b=0;//b的类型为int&及   decltype (func3 (10.5)), c=0;//c的类型为int   ,   decltype (func4 (1、2、3), x=n;//x的类型为const  int&   decltype (func5 ()), y=0;//y的类型为const  int&,

实验中调用函数时需要带上括号和参数,但这仅仅是形式,并不会真的去执行函数代码

规则3示例:

class 一个{   公众:   ,,int  x;   }   ,   int  main ()   {   const  A  obj;   decltype (obj.x),=0;//的类型为int   decltype ((obj.x)), b=一个;//b的类型为int&   ,   int  n=0, m=0;   decltype (m + n), c=0;//n + m得到一个右值,c的类型为int   decltype (n=n + m), d=c;//n=n + m得到一个左值,d的类型为int 及   return  0;   }

c++ decltype的使用方法