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.
精彩评论