I'm coding a class that has a vector as a private attribute.
The type of the vector ( it can be a concurrent_vector from the TBB library or a std vector) is only known at runtime, depending on a parameter specified by the user.
So the question is, how can I code that? I thought something like this:
1 2 3 4 5 6 7 8 9 10
class A {
private:
void* vec;
public:
A( int type ) {
if ( type == 1 ) {
// convert the void* into std::vector<>
} else {
// convert into a tbb::concurrent_vector
}
That conversion, could it be done by a reinterpret_cast? Or is there another better way to do this?
class A
{
private:
template <typename T> class container
{
public:
virtual ~container() { }
virtual T& operator [] (unsigned index) = 0;
virtualunsigned size() = 0;
virtualvoid push_back(const T&) = 0;
//... any other functions you need
};
template <typename T,typename cntrT> class container_type : public container<T>
{
private:
cntrT m;
public:
virtual T& operator [] (unsigned index) { return m[index]; }
virtualunsigned size() { return m.size(); }
virtualvoid push_back(const T& v) { m.push_back(v); }
//... any other functions you need
};
//=============
container<int>* vec;
//=============
public:
A(int type)
{
if(type == 1) vec = new container_type< int,std::vector<int> >;
else vec = new container_type< int,tbb::concurrent_vector<int> >;
// the advantage here is that you only have to check the type when you create it
// once it's created, you can access the vector all with the same type:
(*vec)[5] = whatever; //
}
};
But like I said... not pretty.
Again this really seems like something you shouldn't be trying to do. Why can't you just pick a container type and stick with it?