1

I'm relatively new to C++, and am trying for the first time to build a complex template structure.

How can I declare, as member of a template class Foo, a std::vector of Foo* elements, but that could be of various types?

#include <vector>

template <typename T>
class Foo {
    T mValue;
    std::vector< Foo<T>* > mFooParameters;  // <---- I would like this vector to contain
                                            //       any sort of Foo<T>* elements,
                                            //       Foo<int>*, Foo<double>*, etc.
};

Is it straightforward, possible but complicated, or impossible?

Thank you for your answers!

nenj
  • 119
  • 9
  • I think this is a duplicate of http://stackoverflow.com/questions/6274136/objects-of-different-classes-in-a-single-vector, but I fail to understand how the text of your question relates to its title. – jogojapan Oct 19 '12 at 04:02
  • Thank you jogojapan. It's probably because I got lost in the template thingy. I'm looking into your link! – nenj Oct 19 '12 at 04:04
  • So, is it a duplicate? (If not, what is the difference?) – jogojapan Oct 19 '12 at 04:10
  • It is not completely a duplicate in that I thought there was a difficulty intrinsic to my using templates. Polymorphism is the answer though, see my comment to @h3nr1x 's answer. – nenj Oct 19 '12 at 04:18

1 Answers1

0

If your vector types are all related, use polymorphism as explained in the link provided by @jogojapan, if the types are not related at all, use a vector of void* to hold pointers to your data (kind of messy though)

higuaro
  • 15,730
  • 4
  • 36
  • 43
  • I think I'll use polymorphism to top all possible `Foo` with a unique, more general definition. Thank you! – nenj Oct 19 '12 at 04:17