代码之家  ›  专栏  ›  技术社区  ›  stevendesu

如何使用C++期望操作符?

  •  0
  • stevendesu  · 技术社区  · 7 年前

    我的目标是尽我最大的努力遵循 C++ Core Guidelines 当我努力避免错误、提高性能时,最重要的是:提高代码的可维护性。

    我遇到了很多麻烦 从我的G++/Clang +版本不适合标准库的问题,没有发现G++使用错误的C++版本编译到非常不符合预期的基本功能。 ,所以我预计接下来还会有更多的头痛。

    不过,这个问题是C++核心指南的一部分。 Interfaces 6: Prefer Expects() for expressing preconditions

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

    #include <iostream>
    
    using namespace std;
    
    int square(int x) {
        Expects(x > 0);
        return x * x;
    }
    
    int main() {
        cout << square(3) << endl;
        return 0;
    }
    

    $> 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]
    

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

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

    我还没想好怎么修那个,所以我不想麻烦了。

    2 回复  |  直到 7 年前
        1
  •  6
  •   Mário Feroldi    7 年前

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

    如果你只需要合同部分( 期望 Ensures 等等),只包括 gsl/gsl_assert 标题。例如: gsl_assert from Microsoft . Martin的实现没有进行分离,因此您必须包含 entire GSL header

        2
  •  1
  •   lzervos    7 年前

    除了GSL, Excepts 也存在于 C++20 歪投球 C++17 有点不同的语法

    推荐文章