开发者

Help needed with container for a generic item in C++

I wonder if it is possible to define a generic C++ container that stores items as follow开发者_开发知识库s:

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?


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.


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>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜