我可以 运行 函数返回引用的不同逻辑,具体取决于它是用作左值还是右值?

Can I run different logic for a function returning reference depending on whether it's used as lvalue or rvalue?

考虑以下代码:

#include <iostream>

struct Foo {
  int x;
  int& val() { 
    return x; 
  }
};

int main() {
  Foo foo;
  foo.val() = 2;
  int y = foo.val();
}

在main函数中,foo.val()有时作为左值,有时作为右值。我想根据它的使用方式将逻辑放在 val() 函数的定义中。这可能吗?

In the main function, foo.val() is sometimes used as lvalue and sometimes as rvalue. I would like to to put logic inside the definition of val() function depending on how it's being used. Is that possible

没有直接的方法可以做你想做的事。

但是,您 可以 将整数包装在包装器 class 中并使用转换运算符 operator int&operator= 来实现您想要的想要:

#include <iostream>
#include <functional>

class Foo {
    template <typename T>
    struct Wrapped {
        std::reference_wrapper<T> x;
        Wrapped(Wrapped<T> const& rhs) : x(std::ref(rhs.x.get())) {
            std::cout << "rvalue" << std::endl;
        }
        Wrapped(T& x) : x(std::ref(x)) {}
        Wrapped<T>& operator=(T const& a) {
            std::cout << "lvalue" << std::endl;
            x.get() = a;
            return *this;
        }
        operator T&() {
            std::cout << "rvalue" << std::endl;
            return x.get();
        }
    };
    Wrapped<int> x_w = Wrapped<int>(x);
public:
    int x;
    Wrapped<int>& val() {
        return x_w; 
    }
};

int main() {
    Foo foo;
    foo.val() = 2;      // lvalue
    int y = foo.val();  // rvalue
    auto z = foo.val(); // rvalue
}