I have a class Foo that encapsulates access to a vector and provides access to it via the subscript operator:
typedef int* IntPtr;
class Foo {
std::vector<IntPtr> bars;
IntPtr& operator[](size_t idx) {
return bars[idx];
}
};
In class Bar i want to use Foo. While solution 1 works, it is rather inconvenient. I would prefer something like solution 2. Obviously, a method call (even if it returns an lvalue) can't be assigned something, albeit the method call doesn't do anything else than solution 1.
class Bar {
Foo *foo; //some initialization
IntPtr helper(size_t idx) {
return (*foo)[idx];
}
void barfoo() {
size_t baz = 1;
IntPtr qux;
//solution 1
qux = (*foo)[baz]; //works
(*foo)[baz] = &1; //works
//solution 2
qux = helper(baz); //works
helper(baz) = &1; //does not work: "expression is not assignable"
}
};
Question: How can I simplify the usage of an overloaded subscript operator?
EDIT: Changed used type to from int to int*. Sorry, I screwed up when creating the example.
I guess the problem is because of the twisted int*&.
Foo::operator[]). You certainly can assign to an lvalue reference returned by a function. Are you sure the error comes from that code?