动态更改类属性的类型

isn*_*ork 3 c++

我正在编写一个具有向量作为私有属性的类.向量的类型(可以是TBB库中的concurrent_vector或std向量)仅在运行时已知,具体取决于用户指定的参数.

所以问题是,我该如何编码呢?我想的是:


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
      }
  }
};

那个转换,可以通过reinterpret_cast来完成吗?或者还有另一种更好的方法吗?

我在空白.谢谢你的时间.

Joh*_*itb 6

如果您有一组固定的类型,则boost::variant<>可能是合适的解决方案.

boost::variant< tbb::concurrent_vector<int>, std::vector<int> > member;
Run Code Online (Sandbox Code Playgroud)

它的好处是速度快(它不使用new,但将矢量存储到位),并为您跟踪类型.如果未修复可能类型的集合,则可以使用boost::any

boost::any member;
Run Code Online (Sandbox Code Playgroud)

但是,您需要跟踪自己存储的类型.