C++11 auto和decltype关键字

时间:2020-04-01
本文章向大家介绍C++11 auto和decltype关键字,主要包括C++11 auto和decltype关键字使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今天来看下C++中的auto和decltype两个关键字

  • 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 >::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*

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;
}

参考:http://c.biancheng.net/view/438.html

原文地址:https://www.cnblogs.com/whiteBear/p/12614925.html