Skip to content

Instantly share code, notes, and snippets.

@sudoLife
Last active August 7, 2023 07:37
Show Gist options
  • Save sudoLife/a9b5848a18a3c2b28636c85b85c2f178 to your computer and use it in GitHub Desktop.
Save sudoLife/a9b5848a18a3c2b28636c85b85c2f178 to your computer and use it in GitHub Desktop.
A C++ status variable class that throws when there is a status code indicating a problem.
// The status_variable class is a templated class that is used to handle the status
// of a variable with a predefined success code. Any assignment to this variable
// that does not match the success code results in an exception being thrown.
template <typename T>
class status_variable
{
public:
status_variable() = default;
explicit status_variable(int success_code) : success_code(success_code) {}
void operator=(T other)
{
if (other != success_code)
{
throw std::runtime_error(fmt::format("Error in status, expected value {}, got {}", success_code, other));
}
}
private:
T success_code = 0;
};
@sudoLife
Copy link
Author

sudoLife commented Aug 7, 2023

An example usage is like so:

status_variable<int> status;

try
{
    status = some_op();
    status = some_op2();
catch (...)
{
    // catch logic
}

The whole thing is useful if you have a bunch of similar calls with the same success status code, and you don't want to try and catch each and every one of them separately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment