I'm making a game for the console, and I have run into a bit of a problem: a lot of the game revolves on buying and selling items, and I can't work out a good way to have an inventory system. My general goals are to have each of the following:
-Everything defined in a class
-Cost, name, weight, etc.
-The ability to add an item to the inventory by referring to an item with an ID(like 002 or 935 or something)
template<typename Item_Type, unsignedint capacity>
class Container
{
public:
Container(void)
{
}
// Returns true if the item was added successfully, false if the container was full
bool add(const Item_Type& item)
{
if(capacity > items.size())
{
items.push_back(item);
//item.onInsertionFailed() /* A trick I've done in the past to give custom behavior */
returntrue;
}
returnfalse;
}
unsignedint getCapacity(void) const
{
return capacity;
}
unsignedint getSize(void) const
{
return items.size();
}
// May throw
const Item_Type& get(unsignedint index) const
{
return items.at(index);
}
// Returns true if the index was removed, false if the index was out of bounds
bool remove(unsignedint index)
{
if(index < items.size())
{
items.erase(items.begin() + index);
returntrue;
}
returnfalse;
}
~Container(void)
{
}
private:
std::vector<Item_Type> items;
};
class MyItem
{
};
int main()
{
Container<MyItem, 30> inventory; // Make a container that can hold 30 MyItems
inventory.add(MyItem());
const MyItem& item = inventory.get(0);
inventory.remove(0);
return 0;
}