C++ 是否可以重载右值引用的一元减号运算符?
C++ is it possible to overload the unary minus operator of an rvalue reference?
是否可以区分这两种方法?
在这种情况下看起来完全可以重用时,不应该改变右值吗?
TYPE a;
TYPE b = -a; // unary operator- of a TYPE& aka lvalue ref
TYPE c = -(a+b); // unary operator- of a TYPE&& aka rvalue ref
类似于:
class Type
{
public:
Type& operator -() && { std::cout << "rvalue\n"; return *this; }
Type& operator -() & { std::cout << "lvalue\n"; return *this; }
};
您可以使用 reference qualifier-s(或标准中的引用限定符)
http://coliru.stacked-crooked.com/a/40905649dc0c14e7
示例:
#include <iostream>
#include <string>
#include <vector>
class X
{
public:
int n;
X(const X&) = default;
X() : n(0) {}
X(int n) : n(n) {}
X operator- () const & // lvalue ref-qualifier
{
std::cout << "&\n";
X x(-n);
return x;
}
X operator- () const && // rvalue ref-qualifier
{
std::cout << "&&\n";
X x(-n);
return x;
}
friend X operator+(const X& lhs, const X& rhs) {
return X(lhs.n + rhs.n);
}
};
int main()
{
X a;
X b = -a; // unary operator- of a TYPE& aka lvalue ref
X c = -(a+b);
}
输出:
&
&&
是否可以区分这两种方法? 在这种情况下看起来完全可以重用时,不应该改变右值吗?
TYPE a;
TYPE b = -a; // unary operator- of a TYPE& aka lvalue ref
TYPE c = -(a+b); // unary operator- of a TYPE&& aka rvalue ref
类似于:
class Type
{
public:
Type& operator -() && { std::cout << "rvalue\n"; return *this; }
Type& operator -() & { std::cout << "lvalue\n"; return *this; }
};
您可以使用 reference qualifier-s(或标准中的引用限定符)
http://coliru.stacked-crooked.com/a/40905649dc0c14e7
示例:
#include <iostream>
#include <string>
#include <vector>
class X
{
public:
int n;
X(const X&) = default;
X() : n(0) {}
X(int n) : n(n) {}
X operator- () const & // lvalue ref-qualifier
{
std::cout << "&\n";
X x(-n);
return x;
}
X operator- () const && // rvalue ref-qualifier
{
std::cout << "&&\n";
X x(-n);
return x;
}
friend X operator+(const X& lhs, const X& rhs) {
return X(lhs.n + rhs.n);
}
};
int main()
{
X a;
X b = -a; // unary operator- of a TYPE& aka lvalue ref
X c = -(a+b);
}
输出:
&
&&