Evening all,
I am open to suggestions with this problem.
I have a class setup that resembles the following:
Code:
#include <vector>
#include <numeric> // std::iota
#include <cstdio> // just 'cause I loves printf()
class Base
{
protected:
using Object = std::vector<int>;
private:
Object embedded;
public:
Base(int i)
{
embedded.resize(i);
std::iota(embedded.begin(), embedded.end(), 0);
}
protected:
void replace(Object const& x) { embedded = x; }
void resize(int i) { embedded.resize(i); }
public:
int * data() { return embedded.data(); }
int const* data() const { return embedded.data(); }
Object const& get_embedded() const { return embedded; }
};
void NonMemberFunction(std::vector<int>& eee)
{
if (eee.size() > 0)
{
eee.data()[0] = 103;
}
}
class Derived : public Base
{
public:
Derived(int i) : Base(i) { }
void MemberFunction()
{
Object temp(get_embedded());
NonMemberFunction(temp);
replace(temp);
}
};
int main()
{
Derived foo(7);
foo.data()[1] = 36;
foo.data()[5] = 49;
foo.MemberFunction();
for (int i=0; i<foo.get_embedded().size(); ++i)
printf("%d %d\n", i, foo.data()[i]);
}
So, briefly:
(1) Base has an embedded container-type Object.
(2) Anybody can access the attributes of the Object via get_embedded().
(3) Anybody can mutate the entries of the Object -- that's perfectly fine, but:
(4) Only Base and its Derived classes should be able to resize the embedded Object. (This is important.)
The MemberFunction of the Derived class shows the problem. Since the NonMemberFunction doesn't attempt to resize its argument, one would think there should be some way of passing the embedded Object straight from Derived::MemberFunction to the NonMemberFunction, via the latter's argument list. But of course point (4) demands that the embedded Object be passed by constant reference only. So I've fallen back on passing a local copy back and forth, which is a lousy kludge, and time consuming too.
Sure, I could let get_embedded() return by non-constant reference -- and bust Base's encapsulation. Badly.
In a nutshell, I need three levels of constness here.
In the actual code, Object is one of my own classes, not an std::vector. My first thought was to find some way of passing the Object as a FixedSizeObject&. The problem there of course is that FixedSizeObject would then have to be the base class of Object, and it doesn't really make sense for the base class to have immutable dimensions, while the derived class can be resized.
I could of course just send the data() pointer into NonMemberFunction as an argument, along with whatever other attributes of Object might be needed. Or perhaps an Object::Iterator would solve the problem?... Anyway, not being a guru, I wanted to see what you guys thought.
Thanks
Grump