美文网首页
C++11 类型推导,auto和decltype

C++11 类型推导,auto和decltype

作者: 深红的眼眸 | 来源:发表于2017-04-14 13:48 被阅读0次

本文根据众多互联网博客内容整理后形成,引用内容的版权归原始作者所有,仅限于学习研究使用,不得用于任何商业用途。

auto – 从初始化中推断数据类型

考虑下面的代码:

auto x = 7;

这里的变量x被整数7初始化,所以x的实际数据类型是int。auto的通用形式如下:

auto x = expression;

这样,这个表达式计算结果的数据类型就是变量x的数据类型。

当数据类型未知或不便书写时,使用auto可让编译器自动根据用以初始化变量的表达式类型来推导变量类型。考虑如下代码:

template<class T> void printall(const vector<T>& v)
{
      // 根据v.begin()的返回值类型自动推断p的数据类型
      for (auto p = v.begin(); p!=v.end(); ++p)
          cout << *p << “n”;
}

为了表示同样的意义,在C++98中,我们不得不这样写:

template<class T> void printall(const vector<T>& v)
{
    for (typename vector<T>::const_iterator p = v.begin();
       p!=v.end(); ++p)
        cout << *p << “n”;
}

当变量的数据类型依赖于模板参数时,如果不使用auto关键字,将很难确定变量的数据类型。例如:

template<class T,classs U> void multiply (const vector<T>& vt,
const vector<U>& vu)
{
    // …
    auto tmp = vt[i]*vu[i];
    // …
}

在这里,tmp的数据类型应该与模板参数T和U相乘之后的结果的数据类型相同。对于程序员来说,要通过模板参数确定tmp的数据类型是一件很困难的事情。但是,对于编译器来说,一旦确定了T和U的数据类型,推断tmp的数据类型将是轻而易举的一件事情。

C++11中引入的auto主要有两种用途:自动类型推断和返回值占位。auto在C++98中的标识临时变量的语义,由于使用极少且多余,就算不使用auto声明,变量依旧拥有自动的生命期, 在C++11中已被删除。注意前后两个标准的auto,完全是两个概念。

int a =10 ; //拥有自动生命期
auto int b = 20 ;//拥有自动生命期
static int c = 30 ;//延长了生命期

1. 自动类型推断
auto自动类型推断,用于从初始化表达式中推断出变量的数据类型。通过auto的自动类型推断,可以大大简化我们的编程工作。下面是一些使用auto的例子。

#include <vector>  
#include <map>  
  
using namespace std;  
  
int main(int argc, char *argv[], char *env[])  
{  
//  auto a;                 // 错误,没有初始化表达式,无法推断出a的类型  
//  auto int a = 10;        // 错误,auto临时变量的语义在C++11中已不存在, 这是旧标准的用法。  
  
    // 1. 自动帮助推导类型  
    auto a = 10;  
    auto c = 'A';  
    auto s("hello");  
  
    // 2. 类型冗长  
    map<int, map<int,int> > map_;  
    map<int, map<int,int>>::const_iterator itr1 = map_.begin();  
    const auto itr2 = map_.begin();  
    auto ptr = []()  
    {  
        std::cout << "hello world" << std::endl;  
    };  
  
    return 0;  
};  
  
// 3. 使用模板技术时,如果某个变量的类型依赖于模板参数,  
// 不使用auto将很难确定变量的类型(使用auto后,将由编译器自动进行确定)。  
template <class T, class U>  
void Multiply(T t, U u)  
{  
    auto v = t * u;  
}  

2. 返回值占位

template <typename T1, typename T2>  
auto compose(T1 t1, T2 t2) -> decltype(t1 + t2)  
{  
   return t1+t2;  
}  
auto v = compose(2, 3.14); // v's type is double  

3.使用注意事项

我们可以使用valatile,pointer(*),reference(&),rvalue reference(&&) 来修饰auto。

auto k = 5;  
auto* pK = new auto(k);  
auto** ppK = new auto(&k);  
const auto n = 6;  

auto不能自动推导成CV-qualifiers(constant & volatile qualifiers),除非被声明为引用类型

const int i = 99;  
auto j = i;       // j is int, rather than const int  
j = 100           // Fine. As j is not constant  
  
// Now let us try to have reference  
auto& k = i;      // Now k is const int&  
k = 100;          // Error. k is constant  
  
// Similarly with volatile qualifer  

如果初始化表达式是引用,则去除引用语义。

int a = 10;
int &b = a;

auto c = b;//c的类型为int而非int&(去除引用)
auto &d = b;//此时c的类型才为int&

c = 100;//a =10;
d = 100;//a =100;

如果初始化表达式为const或volatile(或者两者兼有),则除去const/volatile语义。

const int a1 = 10;
auto b1= a1; //b1的类型为int而非const int(去除const)
const auto c1 = a1;//此时c1的类型为const int
b1 = 100;//合法
c1 = 100;//非法

如果auto关键字带上&号,则不去除const语意。

const int a2 = 10;
auto &b2 = a2;//因为auto带上&,故不去除const,b2类型为const int
b2 = 10; //非法
这是因为如何去掉了const,则b2为a2的非const引用,通过b2可以改变a2的值,则显然是不合理的。

用auto声明的变量必须初始化

auto m; // m should be intialized    

auto不能与其他类型组合连用

auto int p; // 这是旧auto的做法。  

函数和模板参数不能被声明为auto

void MyFunction(auto parameter){} // no auto as method argument  
  
template<auto T> // utter nonsense - not allowed  
void Fun(T t){}  

定义在堆上的变量,使用了auto的表达式必须被初始化

int* p = new auto(0); //fine  
int* pp = new auto(); // should be initialized  
   
auto x = new auto(); // Hmmm ... no intializer  
     
auto* y = new auto(9); // Fine. Here y is a int*  
auto z = new auto(9); //Fine. Here z is a int* (It is not just an int)  

auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作,如sizeof和typeid

int value = 123;  
auto x2 = (auto)value; // no casting using auto  
auto x3 = static_cast<auto>(value); // same as above   

定义在一个auto序列的变量必须始终推导成同一类型

auto a4 = 10, a5 = 20, a6 = 30;//正确
auto b4 = 10, b5 = 20.0, b6 = 'a';//错误,没有推导为同一类型

auto会退化成指向数组的指针,除非被声明为引用

int a[9];  
auto j = a;  
cout<<typeid(j).name()<<endl; // This will print int*  
  
auto& k = a;  
cout<<typeid(k).name()<<endl; // This will print int [9]  

std:prev 与 auto使用
std::prev
std::next
std::advance的使用在上面有链接,方法与prev和next相似,只是无返回指针,这里不进行说明

#include <iostream>
#include <iterator>
#include <vector>

int main()
{
  std::vector<int> v{ 3, 1, 4 };
  auto it = v.begin();
  auto nx = std::next(it, 2);
  std::cout << *it << ' ' << *nx << '\n';
  
  it = v.end();
  auto pv = std::prev(it, 2);
  std::cout << *pv << '\n';
}

decltype – 推断表达式的数据类型

decltype(E)是一个标识符或者表达式的推断数据类型(“declared type”),它可以用在变量声明中作为变量的数据类型。例如:

void f(const vector<int>& a, vector<float>& b)
{
    // 推断表达式a[0]*b[0]的数据类型,并将其定义为Temp类型
    typedef decltype(a[0]*b[0]) Tmp;
    // 使用Tmp作为数据类型声明变量,创建对象

    for (int i=0; i < b.size(); ++i) {
      Tmp* p = new Tmp(a[i]*b[i]);
      // …
   }
   // …
}

这个想法以“typeof”的形式已经在通用语言中流行很久了,但是,现在使用中的typeof的实现并没有完成,并有一些兼容性问题,所以新标准将其命名为decltype。

如果你仅仅是想根据初始化值为一个变量推断合适的数据类型,那么使用auto是一个更加简单的选择。当你只有需要推断某个表达式的数据类型,例如某个函数调用表达式的计算结果的数据类型,而不是某个变量的数据类型时,你才真正需要delctype。

返回类型后置

考虑一个模板函数

template<typename U, typename V>
??? foo(U u, V v){
    ...
    return u*v;
}

总之我要在这个函数做点事情,最后返回一个u*v类型的东西。返回类型该怎么写?

有了decltype,似乎可以这么:

template<typename U, typename V>
auto foo(U u, V v) -> decltype(u*v){
    return u*v;
}

decltype和auto不同,它不会忽略引用和顶层const修饰。

const int i=0;
int j=0, &r = j;
decltype(i) a; //const int
decltype(r) b; //int& 

最后,比较特别的是,如果decltype里面的表达式被包含在括号中,视为对表达式求值的类型。

decltype((i)) a;//error: a is int& and must be initialized

对i求值返回的是int&。

参考资料

【C++11】新特性——auto的使用 - 清风小阁
C++11初探:类型推导,auto和decltype
【c++11 faq】auto – 从初始化中推断数据类型
【c++11 faq】decltype – 推断表达式的数据类型
C++11特性:auto关键字
c++11 std::prev、std::next、std::advance与auto 使用

相关文章

  • C++11的类型推导详解

    auto & decltype 关于C++11新特性,最先提到的肯定是类型推导,C++11引入了auto和decl...

  • C++11中auto和decltype

    C++11中auto和decltype auto和decltype都是C++11中引进来用于自动推断类型的关键字,...

  • C++11类型推导

    C++11 重新定义了auto 和 decltype 这两个关键字实现了类型推导,让编译器来操心变量的类型。 au...

  • C++11 类型推导,auto和decltype

    本文根据众多互联网博客内容整理后形成,引用内容的版权归原始作者所有,仅限于学习研究使用,不得用于任何商业用途。 a...

  • 模板函数返回类型的演进

    提纲 c++03: trick 方法 c++11: auto->decltype 组合 c++14: 自动推导模板...

  • auto类型推导与const

    auto类型推导规则 C++11中新增了使用auto进行自动类型推断的功能,从此使用容器等复杂类型时,可以简化代码...

  • [C++11阅读][3-3-2]decltype类型推导(上)

    表达式推导 如下面的例子,decltype的类型推导并不是像auto一样从变量声明的初始化获得变量类型,而是以一个...

  • C++雾中风景10:聊聊左值,纯右值与将亡值

    C++11的版本在类型系统上下了很大的功夫,添加了诸如auto,decltype,move等新的关键词来简化代码的...

  • C++11拾穗

    C++11新关键字 alignas:指定对齐大小 alignof:获取对齐大小 decltype auto(重新定...

  • Item 1Understand template type d

    引子 模板类型推导是Modern C++特性auto的基础,但模板类型推导和auto类型推导有一些区别,具体看正文...

网友评论

      本文标题:C++11 类型推导,auto和decltype

      本文链接:https://www.haomeiwen.com/subject/pvpwattx.html