Instead of detouring via void*
, with C++11 just use reinterpret_cast
.
However, the conversion that you desire permits very ungood things:
#include <iostream>
#include <vector>
using namespace std;
class Base {};
class Derived: public Base
{ public: int x; Derived(): x(42) {} };
int main()
{
vector< Derived* > v;
Derived d;
v.push_back( &d );
cout << v.back()->x << endl; // 42
vector< Base* >* pbv =
reinterpret_cast< vector< Base* >* >( &v );
Base b;
pbv->push_back( &b );
cout << v.back()->x << endl; // indeterminate value
}
It's roughly the same issue that you have with converting T**
to T const**
(not permitted, could allow ungood things). The short of it is, don't do this unless you know exactly what you're doing. The longer of it, hm, well, there's not room to discuss it here, but it involves differentiating between mutable and immutable collections, and being very very careful.
edit: as others (who did not address the conversion question) have already stated, a practical solution is a vector of
A
pointers, or smart pointers, and then using C++ polymorphism (i.e. virtual member functions).