派生自模板化的基类
Deriving from templatized base class
我必须建立一个包含不同类型对象的小型数据库。拥有一个基本的模板化类是个好主意,让我们称之为数据库,然后让从中派生其他类。
例如:
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
}
};
这是一个好主意还是更好的解决方案?问题是数据库的定义必须全部内联,这是长代码。
这不是一个不寻常的成语,但通常模板参数要么是类型,要么是需要编译时的整数。您希望通过这样编译大小和分隔符来获得什么?
我建议你让它们成为数据库的成员,在构造函数中初始化。如果您想内联所有内容,请继续。但是,当您只需要它们成为常量时,不要将它们制作为模板参数。
您不需要内联实现模板成员,它们只需要在标头中。一个常见的习惯用法是为实现提供一个单独的标头,并将其包含在主标头的底部。
// foo.hpp
template <typename T>
class foo {
public:
void bar();
};
#include "foo.tpp"
// foo.tpp
template <typename T>
void foo<T>::bar() { /* code here */ }
相关文章:
- 指向基类派生类的 std::unique_ptr 的指针
- 从多个模板化基类派生时出现"隐藏重载的虚函数"警告
- 从模板基类派生是否在派生类声明的点实例化模板
- 使从一个基类派生的类能够使用继承的受保护成员
- C++多态性访问基类派生类字段
- C++派生类的设置属性到从同一基类派生的未知类对象
- 使用void* 参数定义纯虚函数的抽象基类.派生类匹配参数是指向某种类型的指针
- 在C++中,如何使用将保存从基类派生的任何对象的类成员
- 如何测试从依赖于外部系统的外部基类派生的类
- 如何从模板基类派生非模板类
- 在派生类中使用声明并不能隐藏从基类派生的相同函数
- 从具有静态结构的基类派生
- 具有从 c++ 中的非模板基类派生的模板类的事件系统
- C++ 调用从基类派生的覆盖函数
- 不清楚如何在从抽象基类派生的类中实现运算符重载
- 如何正向声明从正向声明的模板基类派生的类
- 是否可以从 std::enable_shared_from_this 和抽象基类派生
- 多态性c++,试图访问从抽象基类派生的类的成员函数
- C++多重继承,基类派生自同一类
- 基类派生类访问-如何