Covariant vectors
Hi all,
I've been looking for a way to simulate covariant, const, vectors for
some time. From another thread, it seems as though vectors are supposed
to be allocated contiguously.
So I wonder if the technique below is safe and legal in the general
case. In particular, I'm not sure if given virtual or multiple
inheritance, the pointers would be adjusted properly.
// Foo.hpp
struct Base { int a; };
void Foo(Base*, size_t);
// Foo.cpp
#include <iostream>
#include "Foo.hpp"
void Foo(Base* array, size_t size)
{
for (size_t i = 0; i < size; ++i)
std::cout << array[i].a << std::endl;
}
// Bar.cpp
#include <vector>
#include "Foo.hpp"
struct Derived : public Base {};
template <class VectorT>
void ApplyFoo(VectorT& v)
{
Foo(v.empty() ? NULL : &v[0], v.size());
};
void Bar()
{
std::vector<Base> bases;
std::vector<Derived> deriveds;
ApplyFoo(bases);
ApplyFoo(deriveds);
}
If unsafe, is there a way to make it safe?
Also, are there other (simpler?) ways to create and use covariant
*const* containers? By const I mean that the container is not changed,
only its items are read.
Thanks!
-Al-
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]