|
-
May 26th, 2015, 10:03 PM
#17
Re: Vector of Templates Problem
 Originally Posted by Fateslayer
so that means vector which can hold any data type will maybe come in the future versions of c++.
You can store any pointer data type already in a vector since you can upcast any pointer to void*. And you can always downcast a void* pointer again to its actual type although this will not be typesafe (it can result in a runtime error if you downcast to the wrong type).
This is the case now and it will be so in the future. Note that boost::any does not change this even if it's include in the C++ standard.
Your problem can easily be handled by way of the so called Visitor design pattern. It's the object oriented way to accomplish typesafe downcasts.
But you can also use the (maybe more straight forward) void* way. All you need to do is associating each void* pointer with a tag indicating the actual type (and then use the tag information to downcast each void* to its actual type when needed).
So this is what you would store in a vector in principle,
Code:
struct Any {
int tag; // does not have to be an int but should indicate the actual type of ptr
void* ptr; // ptr is downcasted before use to the actual type using the tag info
};
//
std::vector<Any> anyVec;
Finally, with proper design you rarely need to resort to any kind of downcasting at all. (In fact every downcast is best viewed as a design failure and you should go to great lengths to remove them.)
Last edited by razzle; May 26th, 2015 at 10:48 PM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|