0

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!

Ash
  • 3
  • 2
  • While this approach may seem tempting, I don't think it's a terribly good design. In general, I/O code (including database access) should be separated from business model objects (i.e. the structs and collections you're building). The usual idiom is something like this: – Stabledog Jun 23 '13 at 14:57
  • 1- create an entity object (i.e. 'customer') 2- create a database-connection wrapper (something that abstracts the database connection string 3- Create a loader object which knows how to pull data from the database and populate your entity(ies). 4- apply the loader to the entities to fill them. In the opposite direction, the loader needs to detect new records which don't have a primary key and determine the key, push that into the entity, and then do inserts in the database to sync it up. Usually these "ORM frameworks" end up with a lot of auto-generated code from a tool. – Stabledog Jun 23 '13 at 15:01
  • I'm sure you're right, but I don't actually want to send any of this data back. I'm just querying the data so that I can use it for some resource allocation calculation. However, if I ever get into the situation where I want to modify the data tables, I'll make sure to come and re-read your suggestion. – Ash Jun 23 '13 at 15:25

2 Answers2

0

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.

Balog Pal
  • 16,195
  • 2
  • 23
  • 37
  • Thanks so much. Something about that feels like it's cheating, but at least it's functional. – Ash Jun 23 '13 at 15:18
0

try this

template <class T> void Database::newRecord(T& Type, int& key)
{
    typedef Type::value_type type;
    Type.push_back( type() );
    key = Type.size()-1;
    Type[key].PK = key;
}
yngccc
  • 5,594
  • 2
  • 23
  • 33