clang format函数和错误检查在同一行

clang-format Function and error check in the same line

本文关键字:一行 函数 format 错误 检查 clang      更新时间:2023-10-16

我很难设置clang格式,以允许这种格式的短行,

ierr = fun(); CHKERRQ(ierr);

clang格式断线,结果

ierr = fun(); 
CHKERRQ(ierr);

这是一个解决方案,停止叮当声打破短线?或者这在原则上是错误的想法格式化这样的代码。非常感谢任何建议。


编辑:遵循Guillaume答案

事实上,我有一个稍微复杂一点的问题,不同类型的错误代码由两个库返回,特别是PETSc和MoAB。此外,这个系统有自己的错误代码,需要处理。所有这些都不会影响效率。

struct ErrorCheckerCode {
inline void operator<<(const MoFEMErrorCode err) {
if (PetscUnlikely(err)) {
// Handle & thorw PETSc/MoFEM error
}
return;
}
inline void
operator<<(const moab::ErrorCode err) {
if (PetscLikely(MB_SUCCESS != err)) {
// Handle & trow MOAB error 
}
return;
}
static const char *fUNC;
static const char *fILE;
static int lINE;
};
struct ErrorCheckerFunction {
inline ErrorCheckerCode operator<<(const char *func) {
ErrorCheckerCode::fUNC = func;
return ErrorCheckerCode();
}
};
struct ErrorCheckerFile {
inline ErrorCheckerFunction operator<<(const char *file) {
ErrorCheckerCode::fILE = file;
return ErrorCheckerFunction();
}
};
struct ErrorCheckerLine {
inline ErrorCheckerFile operator<<(int line) {
ErrorCheckerCode::lINE = line;
return ErrorCheckerFile();
}
};

定义如下:

#define CHKERR                                                                 
ErrorCheckerLine() << __LINE__ << __FILE__ << PETSC_FUNCTION_NAME <<

所以最后我可以处理像这样的错误

CHKERR fun_moab();
CHKERR fun_petsc();
CHKERR fun_mofem();

这种实现是必不可少的,所以必须以最佳方式进行,我想知道是否可以以更简单、更有效的方式进行非常欢迎批评或建议

注意:

作为表扬。有趣的是,代码的格式化触发了这种类型的开发。

我经常使用clang格式,我认为它无法实现这种格式。

我在使用OpenGL和DirectX的库中经常遇到这种模式。您有一个带有错误代码的API或OpenGL中的错误堆栈,每个函数都可能失败或发出警告。你希望你的代码在发布时得到优化,并且仍然有一个调试模式来准确地找到哪里出了问题,以防你发现错误。

有些库提供了某种可以设置的错误回调,每次出现相关错误时都会有效地调用这些回调。

如果您想要更自定义的东西,或者没有提供错误回调,您可以编写一个简单的包装器,进行系统的错误检查和警告日志记录。

有了这些解决方案,您甚至可以实现一些机制来在运行时激活调试。

现在,如果您正在编写返回以这种方式返回的错误的库或函数,您可能希望使用调试回调策略将调试模式直接包含在库中。


现在,如果您想坚持使用宏解决方案,您可以执行以下操作:

struct ErrorChecker
{
ErrorChecker& operator << (int ierr)
{
// Error checking code
return *this;
}
};
#define CHKERR ErrorChecker() <<

然后

CHKERR fun();