我需要从一个基类创建多个类(超过 50 个),唯一的区别在于派生类的名称。
例如,我的基类定义为:
class BaseError : public std::exception
{
private:
int osErrorCode;
const std::string errorMsg;
public:
int ec;
BaseError () : std::exception(), errorMsg() {}
BaseError (int errorCode, int osErrCode, const std::string& msg)
: std::exception(), errorMsg(msg)
{
ec = errorCode;
osErrorCode = osErrCode;
}
BaseError (const BaseError& other)
: std::exception(other), errorMsg(other.errorMsg)
{
ec = other.errorCode;
osErrorCode = other.osErrorCode;
}
const std::string& errorMessage() const { return errorMsg; }
virtual ~BaseError() throw(){}
}
我必须从这个基类创建很多派生类,每个派生类都有自己的构造函数、复制构造函数和虚拟析构函数,目前我正在复制/粘贴代码,在必要时更改名称:
class FileError : public BaseError{
private:
const std::string error_msg;
public:
FileError () :BaseError(), error_msg() {}
FileError (int errorCode, int osErrorCode, const std::string& errorMessage)
:BaseError(errorCode, osErrorCode, errorMessage){}
virtual ~FileError() throw(){}
};
问题:是否有某种方法可以使用模板创建这些类,这样就不会重复执行?