如何使用 C++ Expects 运算符?

ste*_*esu 8 c++ cpp-core-guidelines c++17

我正在使用 C++ 开始一个项目,我之前在少数学校项目之外从未使用过它 - 远不及我现在正在处理的范围。

我的目标是在我努力避免错误、提高性能以及最重要的是:提高代码的可维护性时,尽我最大的努力遵循C++ 核心指南

我已经遇到了数百个问题,从我的 g++/Clang++ 版本不正确到标准库没有被发现到 g++ 使用错误版本的 C++ 编译到非常基本的函数没有按预期运行 -而我没有甚至开始研究 autotools,所以我预计会有更多的麻烦。

不过,这个问题特定于 C++ 核心指南的一部分。接口 6:优先使用 Expects() 来表达前提条件

我尝试编写以下简单代码:

#include <iostream>

using namespace std;

int square(int x) {
    Expects(x > 0);
    return x * x;
}

int main() {
    cout << square(3) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这在 g++ 中引发了一个错误:

$> g++ -std=c++17 main.cpp
main.cpp: In function ‘int square(int)’:
main.cpp:7:2: error: ‘Expects’ was not declared in this scope
  Expects(x > 0);
  ^~~~~~~
-> [1]
Run Code Online (Sandbox Code Playgroud)

我也尝试使用 Clang,但它有一个完全不同(且不相关)的问题:

$> clang++ -x c++ main.cpp
main.cpp:1:10: fatal error: 'iostream' file not found
#include <iostream>
         ^~~~~~~~~~
1 error generated.
-> [1]
Run Code Online (Sandbox Code Playgroud)

我还没有想出如何解决这个问题,所以我不打扰它。

Már*_*ldi 6

Expects是 GSL 库的一部分。你必须使用一些 GSL 库实现,你可以在 Github 上找到:

这些是我头顶上的那些。

如果你只需要在合同的一部分(ExpectsEnsures等等),就包括了gsl/gsl_assert头。例如:来自 Microsoft 的 gsl_assert。Martin 的实现没有进行分离,因此您必须包含整个 GSL 标头

  • 阅读关于如何很好地使用 C++ 的“指南”并找到非标准的建议是很奇怪的。 (4认同)