How to force a compile error in C++(17) if a function return value isn’t checked? Ideally through the type system

We are writing safety critical code and I'd like a stronger way than [[nodiscard]] to ensure that checking of function return values is caught by the compiler.

Constraints:

  • MSVC++ 2019
  • Something that doesn't rely on warnings
  • Warnings-as-Errors also doesn't work
  • It's not feasible to constantly run static analysis
  • Macros are OK
  • Not a runtime check, but caught by the compiler
  • Not exception based

I've been trying to think how to create a type(s) that, if it's not assigned to a variable from a function return, the compiler flags an error.

Example:

struct MustCheck
{
  bool success;
  ...???... 
};

MustCheck DoSomething( args )
{
  ...
  return MustCheck{true};
}

int main(void) {
  MustCheck res = DoSomething(blah);
  if( !res.success ) { exit(-1); }

  DoSomething( bloop ); // <------- compiler error
}
  

If such a thing is provably impossible through the type system, I'll also accept that answer ;)



Read more here: https://stackoverflow.com/questions/68462879/how-to-force-a-compile-error-in-c17-if-a-function-return-value-isnt-checked

Content Attribution

This content was originally published by daemacles at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: