我必须建立一个包含不同类型对象的小型数据库。有一个基本的模板化类是个好主意吗,我们称它为数据库,然后从中派生其他类。
例如:
template< typename Record,
size_t RECORD_SIZE,
char RECORD_SEP = '!',
char RECORD_PARAM_SEP = ',',
char RECORD_FIELD_SEP = '~',
size_t MAX_RECORDS_PER_QUERY = 5000,
size_t MIN_RECORD_COUNT = 15000
>
class Database
{
public:
typedef Record Record_t;
typedef std::vector< unsigned char > QueryBuffer;
Database( const std::string& basePath, const std::string& recordPath, const std::string tableFilename );
enum class QueryResult
{
OK,
NO_DATA,
OVERFLOW,
FUTURE_DATE,
FUTURE_RANGE,
ERROR
};
void add( void add( const Record_t& r )
{
Lock lock( mMutex );
// ... lots of stuff here
}
QueryResult query(QueryBuffer &qb, time_t first, time_t last )
{
Lock lock( mMutex );
// ... lots of stuff here
}
QueryResult query(QueryBuffer &qb, time_t first )
{
Lock lock( mMutex );
// ... lots of stuff here
}
// protected and private data
};
然后以这种方式派生类
class GameDatabase : public Database< GameType, 9 >
{
private:
using MyBase Database< GameType, 9 >;
public:
GameDatabase( const std::string& basePath )
: MyBase{ basePath, "g/", "g.dat" }
{
}
// another query method
QueryResult query(QueryBuffer &qb, size_t first, size_t last )
{
Lock lock( mMutex );
// use protected methods of MyBase
// .... lots of stuff here
}
};
这是一个好主意还是更好的解决方案?问题是数据库的定义必须全部内联,这是很长的代码。