It's possible to define a pointer to a member and using this later on:
struct foo
{
int a;
int b[2];
};
int main()
{
foo bar;
int foo::* aptr=&foo::a;
bar.a=1;
std::cout << bar.*aptr << std::endl;
}
Now I need to have a pointer to a specific element of an array, so normally I'd write
int foo::* bptr=&(foo::b[0]);
However, the compiler just complains about an "invalid use of non-static data member 'foo::b'
"
Is it possible to do this at all (or at least without unions)?
Edit: I need a pointer to a specific element of an array, so int foo::* ptr
points to the second element of the array (foo::b[1]
).
Yet another edit: I need to access the element in the array by bar.*ptr=2
, as the pointer gets used somewhere else, so it can't be called with bar.*ptr[1]=2
or *ptr=2
.
You can't do that out of the language itself. But you can with boost. Bind a functor to some element of that array and assign it to a
boost::function
:I'm not sure if this will work for you or not, but I wanted to do a similar thing and got around it by approaching the problem from another direction. In my class I had several objects that I wanted to be accessible via a named identifier or iterated over in a loop. Instead of creating member pointers to the objects somewhere in the array, I simply declared all of the objects individually and created a static array of member pointers to the objects.
Like so:
It seems to work for me. I hope that helps.
The problem is, is that accessing an item in an array is another level of indirection from accessing a plain int. If that array was a pointer instead you wouldn't expect to be able to access the int through a member pointer.
What you can do is define member functions that return the int you want:
Then you at least have a consistant interface to allow you to change different values on foo.
all works.
small trick for member and function pointers usage.
try to write
and in compiller error you will see expected type, for your case
int (foo::*)[2]
.EDIT
I'm not sure that what you want is legal without this pointer. For add 1 offset to your pointer you should get pointer on array from your pointer on member array. But you can dereference member pointer without this.
This is because
foo::a
andfoo::b
have different types. More specifically,foo::b
is an array of size 2 ofint
s. Your pointer declaration has to be compatible i.e:Yes, see below:
Updated post with OP's requirements.