Search code examples
c++templatesvectorstructpush-back

Generic Vector Push Back Template


I'm writing some code to interact with a database. My solution is to use vectors of various structs to represent each table within the database. I want to create a template inside my Database class to push_back the vector and insert a new (blank) row; however, I can't figure out what to put inside the "push_back(...)". The following kind of makes sense but isn't working. The key is being returned so that I can interact with the vector inside the class later.

template <class T> void Database::newRecord(T& Type, int& key)
{
    Type.push_back(Type.value_type());
    key = Type.size()-1;
    Type[key].PK = key;
}

I'd call the routine using the following:

vector<table_row> table;
int key;
newRecord(table, key);
table[key]...

the struct looks something like this:

struct table_row {
    int PK;
    ....
};

Thanks!


Solution

  • To me the whole idea reads fishy. But if that is what you want, you can do it without push_back, just do vec.resize(vex.size()+1) than patch up vec.back() as you see fit.

    I'd suggest to forget "empty" records, but add the actual intended content.