目录
持续更新ing
C++11新特性
Template表达式内的空格
vector<vector> > vec; // Ok in each C++ version
vector<vector>> vec; // Ok since C++11
nullptr_t
C++11允许使用nullptr取代0或NULL,用来表示一个指针pointer,指向no value。它是一个新关键字 ,拥有类型为std::nullptr
_t, 它被自动转换为各种pointer,但不会转换为任何整数。
void f(int);
void f(void*);
f(0); // f(int)
f(NULL); // f(int)
f(nullptr); // f(void*)
constexpr
constexpr可用来让表达式核定于编译期
constexpr int square(int x)
{
return x * x;
}
double a[square(9)]; // OK since C++11: a has 81 elements
Variadic Template(可变长模板)
自C++11起,template可拥有“长度不定的参数”,但必须提供一个non-template重载才能结束递归动作。
void print()
{
}
template <typename T,, typename ... Types>
void print(const T& firstArg, const Types& ... args)
{
std::cout << firstArg << std::endl; // print first argument
print(args); // call print() for remaining argements
}
// example
print(7.5, "hello", std::bitset<16>(377), 42);
// output
7.5
hello
0000000101111001
42
Alias Template(带别名的模板)
template <typename T>
using Vec = std::vector<T,, MyAlloc<T>>; // standard vector using own allocator
Vec<int> coo;
// 等价于
std::vector<int, MyAlloc<int>> coll;
Lambda
语法
[函数对象参数] (操作符重载函数参数) mutable 或 exception 声明 -> 返回值类型 {函数体}
捕获
- 空。没有任何函数对象参数。
- =。函数体内可以使用 Lambda 所在范围内所有可见的局部变量(包括 Lambda 所在类的 this),并且是值传递方式(相
当于编译器自动为我们按值传递了所有局部变量)。 - &。函数体内可以使用 Lambda 所在范围内所有可见的局部变量(包括 Lambda 所在类的 this),并且是引用传递方式
(相当于是编译器自动为我们按引用传递了所有局部变量)。 - this。函数体内可以使用 Lambda 所在类中的成员变量。
- a。将 a 按值进行传递。按值进行传递时,函数体内不能修改传递进来的 a 的拷贝,因为默认情况下函数是 const 的,要
修改传递进来的拷贝,可以添加 mutable 修饰符。 - &a。将 a 按引用进行传递。
- a,&b。将 a 按值传递,b 按引用进行传递。
- =,&a,&b。除 a 和 b 按引用进行传递外,其他参数都按值进行传递。
- &,a,b。除 a 和 b 按值进行传递外,其他参数都按引用进行传递。
类型
Lambda的类型是不具名function object,可通过以下方式获取类型
- template 或 auto
- decltype()
- std::function<> class template
#include<functional>
#include<iostream>
std::function<int(int,int)> returnLambda ()
{
return [] (int x, int y) {
return x*y;
};
}
int main()
{
auto lf = returnLambda();
std::cout << lf(6,7) << std::endl;
}