我有一些例外来自std::exception或std::runtime_error.唯一的方法是构造函数explicit MyExceptionX(const char *text = "") : std::exception(text) {}.有没有办法在不使用宏的情况下简化这些代码?
class MyException1: public std::exception
{
public:
explicit MyException1(const char *text = "") : std::exception(text) {}
};
class MyException2: public std::exception
{
public:
explicit MyException2(const char *text = "") : std::exception(text) {}
};
class MyException3: public std::exception
{
public:
explicit MyException3(const char *text = "") : std::exception(text) {}
};
//...
Run Code Online (Sandbox Code Playgroud)
class一切都是公开的,没有必要使用.你可以struct改用.此外,您可以继承构造函数:
struct MyException1: std::exception
{
using std::exception::exception;
};
struct MyException2: std::exception
{
using std::exception::exception;
};
struct MyException3: std::exception
{
using std::exception::exception;
};
Run Code Online (Sandbox Code Playgroud)
此外,如果您真的需要不同的类型,您可以这样做:
template <int>
struct MyException : std::exception
{
using std::exception::exception;
};
using MyException1 = MyException<1>;
using MyException2 = MyException<2>;
using MyException3 = MyException<3>;
Run Code Online (Sandbox Code Playgroud)
如果您想要更具描述性的名称,可以使用enum而不是int.