Skip to content

侯捷C++2.0新特性

语言

Variadic Templates

nullptr/auto

Uniform Initialization

在C++11之前,初始化可能发生在小括号 大括号 复制符号。 现在全部都可以使用大括号。 编译器看到{...},就做出一个initializer_list,关联到一个array。调用函数(如ctor)时array内的元素被分解逐一传给函数

explicit

upload successful

Complex c1(12, 5);
Complex c2 = c1 + 5;

左边编译器会隐式调用构造函数,变成复数加复数。右边会报错。

#include <iostream>
#include <initializer_list>
using namespace std;

class P
{
public:
    P(int a, int b)
    {
        cout << "P(int a, int b)" << endl;
    }

    //P(initializer_list<int>input)
    //{
    //    cout << "initializer_list<int>input" << endl;
    //}

    explicit P(int a, int b, int c)
    {
        cout << "int a, int b, int c" << endl;
    }
};

void fp(const P& input)
{
}

int main()
{
    // ctors
    cout << "ctors" << endl;
    P p1(77, 5); // P(int a, int b)
    P p2{ 77, 5 }; // P(initializer_list<int>input) 
    P p3{ 77, 5, 42 }; // P(initializer_list<int>input) 
    P p4 = { 77, 5 }; // P(initializer_list<int>input) 
    P p5 = { 77, 5, 42 }; // P(initializer_list<int>input),如果删了initializer_list的构造函数
                        //,这句就会报错, error: converting to ‘P’ from initializer
                        //list would use explicit constructor ‘P::P(int, int, int)’
    P p6(77, 5, 42); // explicit P (int a, int b, int c) 
    P p7{ 77, 5, 42, 500 };// P(initializer_list<int>input) 
    P p8 = { 77, 5, 42, 500 };// P(initializer_list<int>input) 
    P p9{ 10 };// P(initializer_list<int>input) 

    // call function
    cout << "call function" << endl;
    fp({ 47, 11 });        // P(initializer_list<int>input)
    fp({ 47, 11, 3 });    // P(initializer_list<int>input)
    fp(P{ 47, 11 });       // P(initializer_list<int>input)
    fp(P{ 47, 11, 3 });    // P(initializer_list<int>input)

    return 0;
}

注释掉initializer_list的构造函数 upload successful

range based for

这个就见的很多了,注意for中也许有隐式的转换。

=delete =default

Alias Template

别名

template <typename T>  
using Vec = std::vector<T, MyAlloc<T>>;

Vec<int> coll; //使用

这个也使用的非常多,把容器包装一下,容器默认的是Alloc,通过这样去使用合适的分配器。

Template Template parameter

Type Alias/noexcept/override/final

Type Alias

类型的别名 //typedef void(func)(int, int); using func = void()(int, int);

decltype

map<string, float> coll;
decltype(coll)::value_type elem; //map<string, float>::value_type elem;

by using the new decltype keyword, you can let the compiler find out the type of an expression. This is the realization of the often requested typeof feature.
application: 1.declare return types 2.use it in metaprogramming 3.pass the type of a lambda

Lambdas

Variadic Templates

”一个和一包“ 模板里变化的是模板参数,参数个数,参数类型,关键字”...“
递归调用,处理的都是参数。使用function templates
递归继承,处理的是类型。使用class templates
例:tuple

标准库

右值引用 Rvalue references

解决不必要的copy
Lvalue:可以出现在=左边
Rvalue:只能出现在=右边  

int a = 1;
int b = 2;
a = b; //ok
b = a; //ok
a = a + b; //ok

a + b = 3; //error

Perfect Forwarding

容器array

容器hashtable