C++ auto和decltype关键字

前言

本文引用于“C语言中文网”,我整理出来放在博客,方便大家共同学习。所有知识点和代码均已亲测可用,如有疑问,可提出,一起讨论学习。

正文

可以用 auto 关键字定义变量,编译器会自动判断变量的类型。例如:

auto i =100; // i 是 int
auto p = new A(); // p 是 A*
auto k = 34343LL; // k 是 long long

有时,变量的类型名特别长,使用 auto 就会很方便。例如:

map <string, int, greater <string> >mp;
for( auto i = mp.begin(); i != mp.end(); ++i)
cout << i -> first << ", " << i -> second;

编译器会自动判断出 i 的类型是 map<string, int, greater<string> >::iterator。

decltype 关键字可以用于求表达式的类型。例如:

int i;
double t;
struct A { double x; };
const A* a = new A();
decltype(a) x1; //x1 是 A*
decltype(i) x2; //x2 是 int
decltype(a -> x) x3; // x3 是 double

在上面的例子中,编译器自动将 decltype (a) 等价为A*,因为编译器知道 a 的类型是A*

auto 和 decltype 可以一起使用。例如:

#include <iostream>
using namespace std;
struct A {
    int i;
    A(int ii) : i(ii) {}
};
A operator + (int n, const A & a)
{
    return A(a.i + n);
}
template <class T1, class T2>
auto add(T1 x, T2 y) -> decltype(x + y) {
    return x + y;
}
int main() {
    auto d = add(100, 1.5); // d 是 double 类型,d = 101.5
    auto k = add(100, A(1)); // k 是 A 类型,因为表达式“100+A(1)”是A类型的
    cout << d << endl;
    cout << k.i << endl;
    return 0;
}

程序的输出结果如下:
101.5
101

第 12 行告诉编译器,add 的返回值类型是decltype(x+y),即返回值的类型和x+y这个表达式的类型一致。编译器将 add 实例化时,会自动推断出x+y的类型。

在 C++11 中,函数返回值若为 auto,则需要和 decltype 配合使用。在 C++14 中,则可以不用 decltype,例如下面的程序没有问题: 

auto add (int a, int b)
{
   int i = a + b;
   return i;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值