Re: Const constructor
Edward Rosten wrote:
So, in a nutshell, here's my complaint. I can write a single C-style
function which operates on immutable data, regardless of whether it's
an array or merely a slice of an array, because pointers are rather
dumb and also const binds differently for *. I can not do the same for
user defined types without making a small hole in the type system.
Const binds always the same, and no need for drilling holes.
Did you read my other post? Because you still speak about
"custom pointers vs built-in pointers" when in fact it is
about "custom arrays vs built-in (evil) arrays"...
Anyway, access to an array is only one part of its interface.
The rest of it is element ownership, copy/assignment.
If you ignore these, there is no need to use anything beside
double * anyway.
Your wish is for a single interface for both classes. This is
how it can be done (names suck though, and this is only
a non-template example)...
class ArrayAccessInterface {
public:
virtual ~ArrayAccessInterface();
virtual double operator[](int index) const = 0;
};
class ArrayAccess : public ArrayAccessInterface {
public:
explicit ArrayAccess(Array<double> const & a)
: m_a(&a) {}
virtual double operator[](int index) const {
return (*m_a)[index];
}
private:
Array<double> const * m_a;
};
class ArraySliceAccess : public ArrayAccessInterface {
public:
explicit ArraySliceAccess(ArraySlice<const double> const & a)
: m_a(&a) {}
virtual double operator[](int index) const {
return (*m_a)[index];
}
private:
ArraySlice<const double> const * m_a;
};
void func(ArrayAccessInterface const & a) { /* bla a[0] bla */ }
Array<double> p; func(ArrayAccess(p));
ArraySlice<const double> q; func(ArraySliceAccess(q));
If you don't like this method, you can write template functions
that will take anything that has operator[] that returns double.
With incoming concepts it can be very clean:
template <typename A>
/* C++0x only */ requires MyCustomArrayOfDoubleConcept<A>
void func(A const & a) { /* bla a[0] bla */ }
Array<double> p; func(p);
ArraySlice<const double> q; func(q);
Now... either choose one of these solutions, or please do as I asked
in the mentioned other post: "... define consistent logic and
semantics from scratch, not related to C++ ..." So make a fictional
syntax/language and define relevant classes and their behavior
the way you would want them to work.
--
Dragan
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]