C++ pointer-to-member if the member is an array

160 Views Asked by At

I have a structure with several members of unsigned short type. The values stored in these types should be in a certain range, so I use a setter method for them that checks the range of the value being assigned.

All these fields have the same value range, so I use the same method for them, with additional argument: pointer-to-member. Here is a working example:

#include <iostream>

struct myStructure {
    unsigned short d1;//a value in range (0..10)
    unsigned short d2;
    bool Set (unsigned short myStructure::*ptr, unsigned short data) {
//this works
        if (data <= 10) {
            this->*ptr = data;
            return true;
        } else {
            return false;
        }
    }
} st {};

int main () {
    st.Set (&myStructure::d1, 2); //changes the value and returns true
    st.Set (&myStructure::d2, 20);//returns false because 20 is out of range
    std::cout << st.d1 << ',' << st.d2 ; //prints "2,0"
    return 0;
}

Now I have the next task: to do the same thing, but the type of the structure member should be an array.

I have declared the following method in the structure:

struct myStructure {
    static const int N_ELEM = 4;
    unsigned short da1[N_ELEM];
    unsigned short da2[N_ELEM];
    bool SetArrayElem (unsigned short myStructure::**ptr , unsigned short index, unsigned short data) {
//how to call this method?
        if ((data <= 10) && (index < N_ELEM)) {
            this->*ptr[index] = data;
            return true;
        } else {
            return false;
        }
    }
} st {};

This code compiles without any error, but I do not know how to call this member.

The following code

    st.SetArrayElem (&myStructure::da1, 2, 5);

fails to be compiled with the following error:

<source>: In function 'int main()':
<source>:20:22: error: cannot convert 'short unsigned int (myStructure::*)[4]' to 'short unsigned int myStructure::**'
   20 |     st.SetArrayElem (&myStructure::da1, 2, 5);
      |                      ^~~~~~~~~~~~~~~~~
      |                      |
      |                      short unsigned int (myStructure::*)[4]

If I replace the type of the first argument of the method declaration to unsigned short myStructure::*ptr[4], nothing changes and I get the same error.

How to create and use a method that works with pointer-to-array-member properly?

1

There are 1 best solutions below

0
molbdnilo On

The membership is a red herring; there is no conversion from "pointer to array" to "pointer to pointer".
(Try int a[4]; int** p = &a; - it won't compile.)

And, as the message says, the type of &myStructure::da1 is short unsigned int (myStructure::*)[4].

What you wrote, unsigned short myStructure::*ptr[4], is an array of unsigned short myStructure::* pointers, which is a very different thing.

This is the same as with regular pointers - if you have int a[4], the type of &a is int (*) [4], not int * [4]