简体   繁体   English

大型项目的C ++异常

[英]C++ exceptions for large project

I'm currently building a C++ game engine as a learning exercise, and am incorporating exceptions into the less performance-critical sections. 我目前正在将C ++游戏引擎构建为学习练习,并将异常纳入对性能要求不高的部分。 I'm primarily a PHP and Ruby developer, so I'm used to declaring new classes of exception on a regular basis using simple syntax like this: 我主要是PHP和Ruby的开发人员,所以我习惯于使用这样的简单语法定期声明新的异常类:

class SomeSubSystemException < Exception; end

or 要么

class SomeSubSystemException extends Exception {};

is there an easy syntax for doing this in C++, or am I going about exception handling the wrong way for C++ projects? 有没有一种简单的语法可以在C ++中执行此操作,还是我打算针对C ++项目使用错误的方式处理异常? Currently I have to do the following for every class of exception, which makes me want to not define very many: 当前,我必须对每个类的异常执行以下操作,这使我不想定义太多异常:

class SubSystemException : public MainException {
    SubSystemException(std::string& msg) : MainException(msg) {}
};

Thanks in advance! 提前致谢!

Define a Macro that does that for you. 定义一个为您执行此操作的宏。

#define NEW_EXC(Derived, Base) class Derived : Base {\
 Derived(const std::string& msg) : Base(msg) {}

NEW_EXC(SubSystemException, MainException);

#undef NEW_EXC

Done. 完成。

Beware macros can be evil. 当心宏可能是邪恶的。

Although I agree with the comment from Bo Person saying that this will not be your main source of boilaerplate, here another way for the heck of it: 尽管我同意Bo Person的评论,即这将不是您的boilaerplate的主要来源,但这里有另一种说法:

Use CRTP 使用CRTP

template<class T>
class MainException : public std::runtime_error{
private:
  MainException(std::string const& msg):std::runtime_error(msg){ }
public:
  static MainException<T> create(std::string const& msg){
    return MainException<T>(msg);
  }
};

//Usage:
class MyException : public MainException<MyException> {};
void foo(){
  MyException::create(std::string("Foo"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM