C++11基础-----decltype关键字

1.decltype关键字获取表达式的类型

int x = 0;
decltype(x) y = 1;  //y -> int

2.推导规则decltype(exp)

  • exp是标识符、类访问表达式,decltype(exp) 和 exp 类型一致
int n = 0;
volatile const int & x = n;

decltype(n) a = n;   //a -> int
decltype(x) b = n;   //b -> const volatile int &
  • exp是函数调用,decltype(exp)和返回值类型一致
const int& fun_cint_r(void);      //左值
const int fun_cint(void);         //纯右值
const Foo fun_cfoo(void);         //纯右值

int x = 0;
decltype(fun_cint_r()) a1 = x;    //a1 -> const int &
decltype(fun_cint())   a2 = 0;    //a2 -> int &
decltype(fun_cfoo())   a3 = 0;    //a3 -> const Foo
注意:按照规则,decltype的结果和函数的返回值类型保持一致。a2是int而不是const int. 而是因为函数返回的是一个纯右值,对于纯右值而言,只有类类型可以携带cv限定符如a3,此外一般忽略掉cv限定符。
  • 其他情况,若exp是一个左值,则decltype(exp)是exp类型的左值引用,否则和exp类型一致
int n = 0, m = 0;
decltype(n + m) c = 0;    //c -> int     左值
decltype(n += m) d = c;   //d -> int &   纯右值

3.返回类型后置语法

#include <stdio.h>
#include <iostream>

using namespace std;


template <typename T, typename U>
auto add(T t, U u) -> decltype(t + u)
{
    return t + u;
}

int& foo(int& i)
{
    i = 10;
    return i;
}

float foo(float& f)
{
    float temp = 1.25;
    f = 5;
    temp += f;
    return temp;
}

template <typename T>
auto func(T& val) -> decltype(foo(val))
{
    return foo(val);
}

int main()
{
        float a = 0, b = 0, sum = 0;

        printf("累加计算器...请输入值:\n");
        scanf("%f,%f",&a,&b);
        sum = add(a, b);
        printf("累加后的和: %f\n", sum);

        float input = 2.3;
        auto result = func(input);
        cout<<"result="<<result<<",input="<<input<<endl;
        int iInput = 1;
        auto iResult = func(iInput);
        cout<<"result="<<iResult<<",input="<<iInput<<endl;

        return 0;
}

学习文献:
《深入应用C++11》

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值