A proxy class to automatically report std::error_code errors.
This class derives from std::error_code and can be used in any C++ standard library call which takes an output parameter of type std::error_code.
The magic is in the destructor of the class. Whenever an instance of this class is destructed, if the object contains an error, the corresponding error message is logged in the associated Report object. Therefore, the standard usage pattern is the following:
std::filesystem::create_directory(dir, &
ErrCodeReport(report, u
"error creating directory", dir));
The first important point is the usage of a constructor, directly as a parameter of the system call, here std::filesystem::create_directory. According to C++ rules, a temporary instance of ErrCodeReport is constructed just before calling create_directory. This instance is then destructed immediately after returning from create_directory. Therefore, in case of error, the error message is automatically logged upon returning from create_directory, before the next instructions.
The second important point is the usage of the "&" operator in front of the constructor. This is a trick to allow the direct usage of a constructor in the function argument list. All system functions which return an error code in a parameter declare that parameter as a non-constant reference to an instance of std::error_code. Because the reference is not constant, the parameter must be an lvalue. And a constructor call is an rvalue, not an lvalue. The operator "&" is redefined in the class and return a non-constant reference to the object. Thus, the expression becomes an lvalue. Note that the choice of "&" is arbitrary and any other unitary operator could have been used instead.
Also note that many apparently redundant constructors are defined. This is a solution to an issue with Microsoft C++. With gcc and clang, calling the first ErrCodeReport constructor with expressions which are convertible to UString is accepted. However, Microsoft C++ generates an obscure error. To avoid that error, a constructor must be found with the exact same paramater types as the values in the constructor call. This is why additional constructors are defined with various common combinations of parameter types. More constructors may need to be defined with new code.