移动语义1: 值类别
题目描述
在C++11后引入了“右值引用”的概念。
与之相对的,我们在课程上所涉及到的概念被称之为“左值引用”。顾名思义,左值引用只能绑定到左值表达式上,而右值引用只能绑定到右值表达式上。我们用T&&类型说明符声明一个右值引用变量,例如:double&& PI = 3.1415926;
右值引用的一个作用是:判断值类别。例如,当一个函数重载了void f(int&)和void f(int&&)时,下列代码会执行相应的预期行为:
int main(){
    int x = 2;
    f(x);  //调用f(int&)
    f(3);  //调用f(int&&)
}因此,可以利用这种方式判断不同的值类别。补全下列代码,使得输出符合预期。
关于输入
无
关于输出
见样例输出
参考答案
#include <iostream>
using std::cout, std::endl;
class A{
public:
    int val;
    A(int x): val(x){}
    friend std::ostream& operator<<(std::ostream &os, const A &a){
        return os << a.val;
    }
};
void f(int& t){
    cout << "lvalue: " << t << endl;
}
void f(double& t){
    cout << "lvalue: " << t << endl;
}
void f(A& t){
    cout << "lvalue: " << t << endl;
}
void f(int&& t){
    cout << "rvalue: " << t << endl;
}
void f(double&& t){
    cout << "rvalue: " << t << endl;
}
void f(A&& t){
    cout << "rvalue: " << t << endl;
}
int main(){
    int x = 1;
    int* p = &x;
    int&& y = 2;
    A a(2);
    f(x);
    f(1);
    f(x + 0.5);
    f(x++);
    f(++x);
    f(*p);
    f(y);
    f(a);
    f(A(5));
    f(a.val);
    f(A(x));
    f(x = 5);
    f((x, 2));
    f((2, x));
}
#include <iostream>
using std::cout, std::endl;
class A{
public:
    int val;
    A(int x): val(x){}
    friend std::ostream& operator<<(std::ostream &os, const A &a){
        return os << a.val;
    }
};
template <typename T>
void f(T& t){
    cout << "lvalue: " << t << endl;
}
template <typename T>
void f(T&& t){
    cout << "rvalue: " << t << endl;
}
int main(){
    int x = 1;
    int* p = &x;
    int&& y = 2;
    A a(2);
    f(x);
    f(1);
    f(x + 0.5);
    f(x++);
    f(++x);
    f(*p);
    f(y);
    f(a);
    f(A(5));
    f(a.val);
    f(A(x));
    f(x = 5);
    f((x, 2));
    f((2, x));
}