c++函数——decltype关键字

decltype使用场景

template<typename T1, typename T2>
void templateFun(T1 x, T2 y)
{
    //  当传入值 x:int, y:double时候
    T1 sum = x + y; // 报错,因为 x + y 为double类型,T1 为int 类型
    // 可以使用decltype关键字解决这个问题
    decltype(x + y) sum = x + y;
    // 使用auto关键字也可以解决
    auto sum = x + y;
    cout << sum << endl;
}

decltype与auto关键字一样,用于进行编译时类型推导。
decltype实际上有点像auto的反函数,auto可以让你声明一个变量,而decltype则可以从一个变量或表达式中得到类型

decltype关键字的规则

decltype(expression) var
  1. expression是一个未用括号括起来的标识符,var的类型和标识符的类型相同,包括const等限定符
    double x = 30.5;
    int y = 20;
    const short sum = 30;
    double &k = x;
    decltype(x) xx;  //  double
    decltype(y) yy;  //  int
    decltype(sum) sum1 = 30;  // const short
    decltype(k) kk = x;  //  double &
  1. expression是一个函数调用,var的类型与函数的返回类型相同
	double fun(int);
	decltype(fun(20)) fun_return = 20.1;  
//  double,并不是实际调用函数,只是利用了函数的返回类型确定变量的类型
  1. expression是一个带括号的标识符,var的类型是标识符对应类型的引用类型
	double xyz = 10.1;
    double value = 20.5;
    decltype((value)) value1 = xyz;  // double &
  1. 以上三种情况都不满足,则var的类型和expression的类型相同
    int m = 20;
    short n = 10;
    decltype(m + n) mn;  // int
    
    decltype(100.1f) valuef;  // float
    
    int &abc = m;
    decltype(m + abc) mabc;  // int
decltype关键字与返回值
int fun1(int x)
{
    return x + x;
}
auto fun2(int x) -> int
{
    return x + x;
}

template <typename T1, typename T2>
auto  fun3(T1 x, T2 y) -> decltype(x+y)
{
   // decltype(x + y) sum = x + y;
   return x + y;
}

int main(int argc, const char * argv[])
{
    auto n = 20;
    auto sum = fun3(3,4);
    cout << sum << endl;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值