How can I map the remote device as an array in C ++?

I would like to create a C ++ object to wrap the RAM of an external peripheral device. I am trying to configure something like the following:

Peripheral p;

p [4] = 10;

int n = p [5];

To do this, I need to read or write to the periphery whenever an array element is accessed. I cannot figure out how to do this using operator overloading etc. I can return an "accessor" object, which can be used as an lvalue in the second line:

PeripheralAccessor Peripheral :: operator [] (int i);

or I can define a “simple” statement that can be used to read int from a peripheral in the third line:

int Peripheral :: operator [] (int i);

but I cannot force them to coexist in order to provide read and write access to the periphery. I can define this second statement as a const (rvalue) statement, but it will ONLY be called for an instance of the const class, which is not enough for my needs ...

Hopefully I explained what I am trying to achieve here clearly; can anyone suggest how i should do this (or is it really possible)?

+3
source share
3 answers

The usual way to handle this is to use a proxy object:

class register_proxy { 
public:
    register_proxy &operator=(int value) { 
        write_value(value);
    }

    operator int() {
        return read_value();
    }
};

class peripheral { 
    register_proxy registers[4];
public:

    register_proxy &operator[](int reg_num) { return registers[reg_num]; }
};

(, register_proxy, / - , ctor). , : operator[] -. - operator int ( , , ) , . - operator= , , .

+3

"PeripheralAccessor" int:

operator int () const;
+2

, ( int, lvalue). PeripheralAccessor int.

Edit: Jerry defeated me. With a code even.

+1
source

Source: https://habr.com/ru/post/1752123/


All Articles