C++ Decltype 关键字

12.1.9 C++ Decltype 关键字

12.1.9.1 问题描述
template<class T1, class T2>
void ft(T1 x, T2 y)
{
    ...
    ?type? xpy = x + y;//C++98 can't explain...,xpy的类型无法描述
    ...
}
12.1.9.2 Decltype 关键字(C++11)

The C++11 solution is a new keyword: decltype.可以这样更改函数:

template<class T1, class T2>
void ft(T1 x, T2 y)
{
    ...
    decltype(x + y) xpy = x + y;
    ...
}

但是decltype是如何评估是什么类型的呢,分为四个步骤,假设有如下声明:

decltype (expression) var;

Stage 1: 如果expresion是一个没有用括号括起的标识符,则var的类型与该标识符的类型相同,包括const等限定符。

double x = 5.5;
double y = 7.9;
double &rx = x;
const double * pd;
decltype(x) w; // w is type double
decltype(rx) u = y; // u is type double &
decltype(pd) v; // v is type const double *

Stage 2: 如果expression是一个函数调用,则var的类型与函数的返回值相同。

long indeed(int);
decltype (indeed(3)) m; // m is type long
//The call expression isn’t evaluated. In this case, the compiler examines the prototype to
get the return type; there’s no need to actually call the function.

Stage 3:如果expression是一个左值,则var为指向其类型的引用。前提是expression是用括号括起的标识符。

double xx = 4.4;
decltype ((xx)) r2 = xx; // r2 is double &
decltype(xx) w = xx; // w is double (Stage 1 match)
//Incidentally, parentheses don’t change the value or lvaluedness of an expression. For
example, the following two statements have the same effect:
xx = 98.6;
(xx) = 98.6; // () don't affect use of xx

Stage 4: 如果前面的条件都不满足,则var的类型与expression的类型相同。

int j = 3;
int &k = j
int &n = j;
decltype(j+6) i1; // i1 type int
decltype(100L) i2; // i2 type long
decltype(k+n) i3; // i3 type int;
//Note that although k and n are references, the expression k+n is not a reference; it’s just
the sum of two ints, hence an int.
12.1.9.3 后置返回值类型

如何确定返回值的类型:

template<class T1, class T2>
?type? gt(T1 x, T2 y)
{
...
    return x + y;
}
//如果继续使用decltype方式的话,当函数返回值时,x,y的存储空间已经收回了,
//所以,不知道应该是什么类型

C++11定义了新的语法:

auto h(int x, float y) -> double;
//-> double成为后置返回类型. 其中auto是一个占位符,表示后置返回类型提供的类型。

结合->和decltype,可以得出如下解决方案:

template<class T1, class T2>
auto gt(T1 x, T2 y) -> decltype(x + y)
{
    ...
    return x + y;
}
//decltype在函数声明后面,因此x和y位于作用域内,可以使用他们。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jasmine-Lily

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值