Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C++ Expects operator?

I'm starting a project using C++, which I haven't used before outside of a handful of school projects - nowhere near the scope of what I'm tackling now.

My goal is to try my best to follow the C++ Core Guidelines as I work to avoid errors, improve performance, and most importantly: improve maintainability of my code.

I've been running into literally hundreds of issues ranging from my g++ / Clang++ versions not being right to standard libraries not being found to g++ using the wrong version of C++ for compilation to very basic functions not behaving as expected - and I haven't even started to look into autotools, so I expect many more headaches to follow.

This question is specific to one part of the C++ Core Guidelines, though. Interfaces 6: Prefer Expects() for expressing preconditions

I tried writing the following simple code:

#include <iostream>

using namespace std;

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

int main() {
    cout << square(3) << endl;
    return 0;
}

This threw an error in 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]

I tried using Clang, as well, but it has an entirely different (and unrelated) problem:

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

I haven't figured out how to fix that one yet, so I'm not bothering with it.

like image 522
stevendesu Avatar asked Feb 04 '19 17:02

stevendesu


2 Answers

Expects is part of the GSL library. You have to use some GSL library implementation, which you can find on Github:

  • https://github.com/martinmoene/gsl-lite
  • https://github.com/Microsoft/GSL

These are the ones I have off the top of my head.

The CPP Guidelines likely allude to the "contracts" proposal which provides the same checks via attributes. It was scheduled for C++20, but later removed for lack of consensus on its scope. See p1823r0 and a standard committee member's Reddit thread on the rationale leading to the removal.

like image 172
Mário Feroldi Avatar answered Nov 07 '22 01:11

Mário Feroldi


Apart from GSL, Excepts exists also in C++20 not in C++17 with a little different syntax

  • https://en.cppreference.com/w/cpp/language/attributes/contract
like image 27
lzervos Avatar answered Nov 07 '22 02:11

lzervos