Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ struct with template in vector

I'm making a text adventure game in C++. This is the struct for an object in that game (something the user can pick up and put in the inventory)

template <int N>
struct Object
{
    static const int length = N;
    string names[N];
    string description;
};

Examples of objects:

Object<2> flower = { {"flower", "the flower"}, "A strange looking flower"};
Object<3> book = { { "the book", "book", "recipe book" }, "The world's finest cocktail recipes now all in one easy to use companion." };

The multiple names are synonyms for the command parser, so the user can input "pick up book" or "pick up recipe book", which in both cases picks up the object book.

Now I'd like to create a vector inventory to store all the elements in the inventory.

vector<Object> inventory;

Now, off course, this gives me a compiler error, because it expects something like this:

vector<Object<5>> inventory;

However, some objects have more names than others, is something like this possible and if so, how?

vector<Object<N>> inventory;
like image 270
William Black Avatar asked Dec 18 '13 13:12

William Black


1 Answers

All your different Object<N> classes are different types with different sizes. You can't put them in a homogenous container.

You would need some base class or base interface, and store pointers in the vector, relying on virtual dispatch and polymorphism when you pull the elements out. This would make your container of Objects a heterogenous container.

Alternatively, and preferably, drop the template and store the names in a member container:

struct Object
{
    set<string> names;
    string description;
};

vector<Object> easy;

PS. I don't consider Object to be a good name for any class. CompuChip's suggestion of InventoryItem makes more sense.

like image 126
Lightness Races in Orbit Avatar answered Sep 27 '22 16:09

Lightness Races in Orbit