C++11中新特性:类型推导
C++11:类型推导
C++11标准为C++编程语言的第三个官方标准,正式名叫ISO/IEC 14882:2011 - Information technology -- Programming languages -- C++。在正式标准发布前,原名C++0x。它将取代C++标准第二版ISO/IEC 14882:2003 - Programming languages -- C++成为C++语言新标准。
C++11是对目前C++语言的扩展和修正, C++11不仅包含核心语言的新机能,而且扩展了C++的标准程序库(STL) ,并入了大部分的C++ Technical Report 1(TR1) 程序库(数学的特殊函数除外)。
C++11包括大量的新特性:包括lambda表达式,类型推导关键字auto、 decltype,和模板的大量改进。
auto
auto的自动类型推导,用于从初始化表达式中推断出变量的数据类型。从这个意义上讲,auto并非一种“类型”声明,而是一个类型声明时的“占位符”,编译器在编译时期会将auto替换为变量实际的类型。
通过auto的自动类型推导,可以大大简化我们的编程工作:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
double foo() {}
void func(vector<string> & tmp)
{
    for (auto i = tmp.begin(); i < tmp.end(); i++)
    {
        // 一些代码
    }
}
int main()
{
    auto x = 1;      // x的类型为int
    auto y = foo();  // y的类型为double
    struct m { int i; }str;
    auto str1 = str;    // str1的类型是struct m
    auto z;     // err, 无法推导,无法通过编译
    z = x;
    return 0;
}
注意点:
void fun(auto x =1) {}  // 1: auto函数参数,有些编译器无法通过编译
struct str
{
    auto var = 10;   // 2: auto非静态成员变量,无法通过编译
};
int main()
{
    char x[3];
    auto y = x;
    auto z[3] = x; // 3: auto数组,无法通过编译
    // 4: auto模板参数(实例化时),无法通过编译
    vector<auto> x = {1};
    return 0;
}
decltype
decltype实际上有点像auto的反函数, auto可以让你声明一个变量,而decltype则可以从一个变量或表达式中得到其类型,如下:
#include <typeinfo>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int i;
    decltype(i) j = 0;
    cout << typeid(j).name() << endl;   // 打印出"int", g++表示i
    float a;
    double b;
    decltype(a + b) c;
    cout << typeid(c).name() << endl;   // 打印出"double", g++表示d
    vector<int> vec;
    typedef decltype(vec.begin()) vectype; // decltype(vec.begin()) 改名为 vectype
    vectype k;  // 这是auto无法做到的
    //decltype(vec.begin()) k;  // 这是auto无法做到的
    for (k = vec.begin(); k < vec.end(); k++)
    {
        // 做一些事情
    }
    enum {Ok, Error, Warning}flag;   // 匿名的枚举变量
    decltype(flag) tmp = Ok;
    return 0;
}
追踪返回类型
返回类型后置:在函数名和参数列表后面指定返回类型。
int func(int, int);
auto func2(int, int) -> int;
template<typename T1, typename T2>
auto sum(const T1 & t1, const T2 & t2) -> decltype(t1 + t2)
{
    return t1 + t2;
}
template <typename T1, typename T2>
auto mul(const T1 & t1, const T2 & t2) -> decltype(t1 * t2)
{
    return t1 * t2;
}
int main()
{
    auto a = 3;
    auto b = 4L;
    auto pi = 3.14;
    auto c = mul( sum(a, b), pi );
    cout << c << endl;  // 21.98
    return 0;
}
    永远相信美好的事情即将发生。

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号