c++ :auto

转载:http://towriting.com/blog/2013/08/08/improved-type-inference-in-cpp11/

C++11引入了一些新的实用的类型推导能力,这意味着你可以花费更少的时间去写那些编译器已经知道的东西。当然有些时候你需要帮助编译器或者你的编程伙伴。但是C++11,你可以在一些乏味的东西上花更少的时间,而多去关注逻辑本身。

auto之乐

在C++11中,如果编译器在定义一个变量的时候可以推断出变量的类型,不用写变量的类型,你只需写auto即可。

int x = 4;
  • 1

现在可以这样写:

auto x = 4;
  • 1

这当然不是auto预期的用途!它会在模板和迭代器的配合使用中闪耀光芒:

vector<int> vec;
auto itr = vec.iterator();
  • 1
  • 2

其它时候auto也会非常有用。比如,你有一些下面格式的代码:

template <typename BuiltType, typename Builder>
void
makeAndProcessObject (const Builder& builder)
{
    BuiltType val = builder.makeObject();
    // do stuff with val
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

上面的代码,我们看到这里需要两个模板参数:一个是Builder对象的类型,另一个是Builder创建出的对象的类型。糟糕的是创建出的类型无法被推导出,所以每次你必须这样调用:

MyObjBuilder builder;
makeAndProcessObject<MyObj>( builder );
  • 1
  • 2

但是auto立即将丑陋的代码一扫无余,当Builder创建对象时不用写特殊代码了,你可以让C++帮你做:

template <typename Builder>
void
makeAndProcessObject (const Builder& builder)
{
    auto val = builder.makeObject();
    // do stuff with val
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

现在你仅需一个模板参数,而且这个参数可以在函数调用的时候轻松推导:

MyObjBuilder builder;
makeAndProcessObject( builder );
  • 1
  • 2

这样更易调用了,并且没丢失可读性,却更清晰了。

decltype和新的返回值语法

现在你可能会说auto就这样吗,假如我想返回Builder创建的对象怎么办?我还是需要提供一个模板参数作为返回值的类型。好!这充分证明了标准委员有一群聪明的家伙,对这个问题他们早想好了一个完美的解决方案。这个方案由两部分组成:decltype和新的返回值语法。

新的返回值语法

让我们讲一下新的返回值语法,这个语法还能看到auto的另一个用处。在以前版本的C和C++中,返回值的类型必须写在函数的前面:

int multiply(int x, int y);
  • 1

在C++11中,你可以把返回类型放在函数声明的后面,用auto代替前面的返回类型,像这样:

auto multiply(int x, int y) -> int;
  • 1

但是为什么我要这样用?让我们看一个证明这个语法好处的例子。一个包含枚举的类:

class Person
{
public:
    enum PersonType { ADULT, CHILD, SENIOR };
    void setPersonType (PersonType person_type);
    PersonType getPersonType ();
private:
    PersonType _person_type;
};

我们写了一个简单的类,里面有一个类型PersonType表明Person是小孩、成人和老人。不做特殊考虑,我们定义这些成员方法时会发生什么? 第一个设置方法,很简单,你可以使用枚举类型PersonType而不会有错误:

void Person::setPersonType (PersonType person_type)
{
    _person_type = person_type;
}
  • 1
  • 2
  • 3
  • 4

而第二个方法却是一团糟。简单的代码却编译不过:

// 编译器不知道PersonType是什么,因为PersonType会在Person类之外使用
PersonType Person::getPersonType ()
{
    return _person_type;
}
  • 1
  • 2
  • 3
  • 4
  • 5

你必须要这样写,才能使返回值正常工作

Person::PersonType Person::getPersonType ()
{
    return _person_type;
}
  • 1
  • 2
  • 3
  • 4

这可能不算大问题,不过会容易出错,尤其是牵连进模板的时候。

这就是新的返回值语法引进的原因。因为函数的返回值出现在函数的最后,而不是前面,你不需要补全类作用域。当编译器解析到返回值的时候,它已经知道返回值属于Person类,所以它也知道PersonType是什么。

auto Person::getPersonType () -> PersonType
{
    return _person_type;
}
  • 1
  • 2
  • 3
  • 4

好,这确实不错,但它真的能帮助我们什么吗?我们还不能使用新的返回值语法去解决我们之前的问题,我们能吗?不能,让我们介绍新的概念:decltype。

decltype

decltype是auto的反面兄弟。auto让你声明了一个指定类型的变量,decltype让你从一个变量(或表达式)中得到类型。我说的是什么?

int x = 3;
decltype(x) y = x; // 相当于 auto y = x;
  • 1
  • 2

可以对基本上任何类型使用decltype,包括函数的返回值。嗯,听起来像个熟悉的问题,假如我们这样写:

decltype( builder.makeObject() )
  • 1

我们将得到makeObject的返回值类型,这能让我们指定makeAndProcessObject的返回类型。我们可以整合进新的返回值语法:

template <typename Builder>
auto
makeAndProcessObject (const Builder& builder) -> decltype( builder.makeObject() )
{
    auto val = builder.makeObject();
    // do stuff with val
    return val;
}

这仅适用于新的返回值语法,因为旧的语法下,我们在声明函数返回值的时候无法引用函数参数,而新语法,所有的参数都是可访问的。

auto:引用、指针和常量

下面要确定的一个问题是auto如何处理引用:

int& foo();

auto bar = foo(); // int& or int?
  • 1
  • 2
  • 3

答案是在C++11中,auto处理引用时默认是值类型,所以下面的代码bar是int。不过你可以指定&作为修饰符强制它作为引用:

int& foo();

auto bar = foo(); // int
auto& baz = foo(); // int&
  • 1
  • 2
  • 3
  • 4

不过,假如你有一个指针auto则自动获取指针类型:

int* foo();

auto p_bar = foo(); // int*

但是你也可以显式指定表明变量是一个指针:

int* foo();
auto *p_baz = foo(); // int*

当处理引用时,你一样可以标记const,如果需要的话:

int& foo();

const auto& baz = foo(); // const int&

或者指针:

int* foo();
const int* const_foo();
const auto* p_bar = foo(); // const int*
auto p_bar = const_foo(); // const int*

所有这些都很自然,并且这遵循C++模板中类型推导的规则。

转载:http://blog.csdn.net/huang_xw/article/details/8760403 

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

1. 自动类型推断

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

[cpp] view plain copy

 print?

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

2. 返回值占位

[cpp] view plain copy

 print?

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

3.使用注意事项

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

[cpp] view plain copy

 print?

  1. auto k = 5;  
  2. auto* pK = new auto(k);  
  3. auto** ppK = new auto(&k);  
  4. const auto n = 6;  

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

[cpp] view plain copy

 print?

  1. auto m; // m should be intialized    

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

[cpp] view plain copy

 print?

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

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

[cpp] view plain copy

 print?

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

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

[cpp] view plain copy

 print?

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

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

[cpp] view plain copy

 print?

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

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

[cpp] view plain copy

 print?

  1. auto x1 = 5, x2 = 5.0, x3='r';  // This is too much....we cannot combine like this  

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

[cpp] view plain copy

 print?

  1. const int i = 99;  
  2. auto j = i;       // j is int, rather than const int  
  3. j = 100           // Fine. As j is not constant  
  4.   
  5. // Now let us try to have reference  
  6. auto& k = i;      // Now k is const int&  
  7. k = 100;          // Error. k is constant  
  8.   
  9. // Similarly with volatile qualifer  

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

[cpp] view plain copy

 print?

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

--------------------- 本文来自 qq_32541007 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/qq_32541007/article/details/52424721?utm_source=copy

猜你喜欢

转载自blog.csdn.net/hunter___/article/details/82893278