Changing the type of a class attribute dinamycally

Hi,

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?

I'm in blank.
Thanks for your time.
Last edited on
void pointers and casting aren't pretty. Then again there isn't really a pretty way to do this.

I have to ask: is this really necessary? It seems like a bad idea to do this.

Anyway, assuming it is necessary...

Other alternatives are to use a all encompassing type like boost::any.

Yet another option would be to create your own wrapper class(es):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class A
{
private:
    template <typename T> class container
    {
    public:
        virtual ~container() { }
        virtual T& operator [] (unsigned index) = 0;
        virtual unsigned size() = 0;
        virtual void 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];  }
        virtual unsigned size()                 { return m.size();  }
        virtual void 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?
Why don't you define A as a template class?

http://www.cprogramming.com/tutorial/templates.html
You may want to go there and see whether it's something you're looking for.
EDIT: Man, I did not read inside the parenthesis in your original post. In this case, +1 for Disch's proposal.

...deleted

Regards
Last edited on
Topic archived. No new replies allowed.