开发者

Dynamically change the type of a class attribute

开发者 https://www.devze.com 2023-02-09 06:31 出处:网络
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 para

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:


class A {
  private:
     void* vec;
  public:
    A( int type ) {
       if ( type == 1 ) {
         // conver开发者_高级运维t 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.


If you have a fixed set of types, a boost::variant<> may be a suitable solution.

boost::variant< tbb::concurrent_vector<int>, std::vector<int> > member;

It has the benefit that it's fast (it does not use new, but stores the vectors in place), and tracks the type for you. If the set of possible types isn't fixed, you can use boost::any

boost::any member;

But then you need to track the type stored yourself.

0

精彩评论

暂无评论...
验证码 换一张
取 消