views:

71

answers:

2

I wonder if it is possible to define a generic C++ container that stores items as follows:

template <typename T>
class Item{
typename T value;
}

I am aware that the declaration needs the definition of the item type such as:

std::vector<Item <int> > items;

Is there any pattern design or wrapper that may solve this issue?

+1  A: 

If you need a container that can hold elements of any type in it then take a look at boost::any.

In your current question there's no big difference between std::vector<Item <int> > and std::vector<int>.

Kirill V. Lyadvinsky
The class Item is storing an object of type T. For example, Item<int> should store an integer in the variable "value".
Ali
What are you trying to achieve? Why you can't just use `vector<int>`?
Kirill V. Lyadvinsky
If the types you want to store in such a container is known at compile time, you can use boost::variant instead of boost::any, which adds some type-safety.
smerlin
@Kirill, What I want to achieve is to define a vector<Item> for 9 kinds of Item<T>. Anyway, I think that boost::any can solve my problem.
Ali
+1  A: 

With 9 types, your best shot is to use boost::variant, in comparison to boost::any you gain:

  • type safety (compile time checks)
  • speed (similar to a union, no heap allocation, no typeid invocation)

Just use this:

typedef boost::variant<Type0, Type1, Type2, Type3, Type4,
                       Type5, Type6, Type7, Type8>        Item;

typedef std::vector<Item> ItemsVector;

In order to invoke an operation on boost::variant, the best way is to use create a static visitor, read about it in the documentation.

Matthieu M.