c++ - 如何实现 `my_class_instance(a, b) = value`操作

标签 c++

我有一个Flight类,我需要实现两个操作:

Flight s;
auto value = s(1, 2);
s(3, 4) = value;
我知道如何执行首次操作:
class Flight 
{
public:
  int operator()(int a, int b) {
     return cache.for(a, b).get();
  }
private:
 // cache  
}
但是我不知道执行第二次操作。像这样:
void operator()=(int a, int b, int value) {
   cache.for(a, b).set(value);
}
现在我有一个类似于operation is not accessible fors(3, 4) = value;表达式错误。
如何执行此操作?

最佳答案

没有()=运算符。它是两个单独的运算符-operator(),然后是operator=的返回值。
由于要在缓存中使用单独的operator()get()方法,因此必须使set()返回帮助代理,然后可以实现Flight::operator()调用proxy::operator int方法和get()调用proxy::operator=方法,例如:

class Flight 
{
public:
    class Proxy
    {
    private:
        Flight &f;
        int a, b;

    public:
        Proxy(Flight &f, int a, int b) : f(f), a(a), b(b) {}

        operator int() {
            return f.cache.For(a, b).get();
        };

        Proxy& operator=(int value) {
            f.cache.For(a, b).set(value);
            return *this;
        }
    };

    friend class Proxy;

    Proxy operator()(int a, int b) {
        return Proxy{*this, a, b};
    }

private:
    // cache
};
然后,您的示例将按需要工作:
Flight s;
int value = s(1, 2); // <-- important - int, not auto!
s(3, 4) = value;
Live Demo

关于c++ - 如何实现 `my_class_instance(a, b) = value`操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63944410/

相关文章:

c++ - 从二进制列表中获取十进制数的递归函数

c++ - 多种数据类型的单个模板对象

C++、委托(delegate)、应用程序崩溃、未知原因

c++ - OpenGL 使用单个 VBO 渲染多个对象,使用另一个 VBO 更新对象的矩阵

c++ - realloc 调用会引入多少开销?

c++ - 优化模板代码编译

c++ - 如何区分某些 LVITEMS(文件或目录)?

c++ - 加载somesound.bank并使用fmod播放c++

c++ - 如何在 C++ 中为多个类创建别名

c++ - FAST 函数 OpenCV 调试断言失败