class A{};
A getA(){
return A();//右值
}
int main() {
int a = 1;
int &ra = a; //OK
const A &ca = getA();//OK
A &aa = getA();//ERROR,右值不能给左值引用
}
右值引用只能绑定在右值上
class A{
int val;
void setVal(int v) {
val = v;
}
};
A getA(){
return A();
}
//知道风险,并且想要改变新对象,就是右值引用&&
int main() {
int a = 1;
int &ra = a; //OK
const A &cra = getA();//OK
A &&aa = getA();//OK
aa.setVal(2);//OK
//…
}
//myfunc.h
template<typename T>
void myfunc(T t){}
//test.cpp
#include "myfunc.h"
int foo(int a){
myfunc(1);
return 1;
}
//main.cpp
#include "myfunc.h"
//如果没有以下的模板,那么编译器会先去实例化模板,新的方式外部模板可以避免多次实例化的问题
/*Tell compiler: this instance has been
instantiated in another module!*/
extern template void myfunc<int>(int);
int main() {
myfunc(1);
}
3. 常量表达式
提供了更一般的常量表达式
允许常量表达式使用用户自定义类型
提供一种方法来确保在编译时完成初始化
必须在编译的时候可以确定常量表达式
3.1. Ex1
enum Flags { GOOD=0, FAIL=1, BAD=2, EOF=3 };
constexpr int operator| (Flags f1, Flags f2) {
return Flags(int(f1)|int(f2));
}//如果不加constexpr则结果被认为是变量不能使用在case中
void f(Flags x) {
switch (x) {
case BAD: /* ... */break;
case EOF: /* ... */ break;
case BAD|EOF: /* ... */ break;//OK,必须是简单的确认的值
default: /* ... */ break;
}
}
void f(Flags x) {
switch (x) {
case bad_c(): /* ... */break;
case eof_c(): /* ... */ break;
case be_c(): /* ... */ break;
default: /* ... */ break;
}
}
constexpr int bad_c();
constexpr int eof_c();
constexpr int be_c();
3.2. Ex2 常量对象
所有评估都可以在编译时完成。 因此,提高了运行时间效率。
编译时确定的
struct Point {
int x,y;
constexpr Point(int xx, int yy) : x(xx), y(yy) { }
};
int main() {
constexpr Point origo(0,0);//完全常量,在常量表上
constexpr int z = origo.x;
constexpr Point a[] = {Point(0,0), Point(1,1), Point(2,2) };
constexpr int x = a[1].x; // x becomes 1
}
4. Lambda Function
Also names as Lambda Expression.
A mechanism for specifying a function object
4.1. Ex1
bool cmpInt(int a, int b) {return a < b;}
class CmpInt {
bool operator()(const int a, const int b) const {
return a < b;
}
};
int main() {
std::vector<int> items { 4, 3, 1, 2 };
std::sort(items.begin(), items.end(), cmpInt); //Function Pointer
std::sort(items.begin(), items.end(), CmpInt()); //Function Object (Functor)
std::sort(items.begin(), items.end(),
[](int a, int b) { return a < b; } //Lambda Function
);
return 0;
}
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp) {
//…
if ( comp(*it1, *it2) )
//…
}
//std::function 是C++对所有可调用的函数的封装
std::function<bool(int, int)> f1(cmpInt);
std::function<bool(int, int)> f2(CmpInt);
std::function<bool(int, int)> f3([](int a, int b) { return a < b;} );